我正在开发 ASP.net Web 窗体,我想在网站中实现 AutoFac。
我已按照以下链接中的步骤操作: https://autofaccn.readthedocs.io/en/latest/integration/webforms.html
但是我得到了这个错误:
This module requires that the HttpApplication (Global Application Class) implements IContainerProviderAccessor.
我在我的项目中找不到Global.asax.cs,只有Global.asax。
Global.asax:
<%@ Application Language="C#" %>
<%@ Import Namespace="Autofac" %>
<%@ Import Namespace="Autofac.Integration.Web" %>
<script RunAt="server">
public class Global : HttpApplication, IContainerProviderAccessor {
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider {
get { return _containerProvider; }
}
void Application_Start(object sender, EventArgs e) {
// Code that runs on application startup
// Build up your application container and register your dependencies.
var builder = new ContainerBuilder();
//builder.RegisterType<SomeDependency>();
// ... continue registering dependencies...
// Once you're done registering things, set the container
// provider up with your registrations.
_containerProvider = new ContainerProvider(builder.Build());
}
}
</script>
有什么想法吗?非常感谢!
请您参考如下方法:
我也有这个问题,并通过创建一个 global.asax.cs 文件并从原始 global.asax 文件中引用它来修复它。这使您能够实现所需的 IContainerProviderAccessor 接口(interface)。
文件:Global.asax
<%@ Application Codebehind="Global.asax.cs" Inherits="MyCompany.WebForms.Global" Language="C#" %>
文件:Global.asax.cs
using Autofac;
using Autofac.Core;
using Autofac.Integration.Web;
using ....
namespace MyCompany.WebForms
{
public partial class Global : HttpApplication, IContainerProviderAccessor
{
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
protected void Application_Start(object sender, EventArgs e)
{
....
}
}
}
在实现这个之后,我也遇到了 Could not load type 'MyCompany.WebForms.Global' 错误的问题,直到我将 Global.asax.cs 文件移动到 < strong>App_Code 文件夹并更新了 CodeBehind 引用 Global.asax。
