在asp.net web表单中实现autofac

Ric*_*Yip 1 c# webforms autofac c#-4.0

我正在开发 ASP.net Web Form,我想在网站中实现 AutoFac。

我已按照以下链接中的步骤操作: https ://autofaccn.readthedocs.io/en/latest/integration/webforms.html

但我收到了这个错误:

该模块要求 HttpApplication(全局应用程序类)实现 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>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?非常感谢!

use*_*466 5

我也遇到了这个问题,并通过创建一个 global.asax.cs 文件并从原始的 global.asax 文件引用它来修复它。这使您能够实现所需的 IContainerProviderAccessor 接口。

文件:Global.asax

<%@ Application Codebehind="Global.asax.cs" Inherits="MyCompany.WebForms.Global" Language="C#" %>
Run Code Online (Sandbox Code Playgroud)

文件: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)
        {
             ....
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实现此操作后,我还遇到了Could not load type 'MyCompany.WebForms.Global'错误的问题,直到我将Global.asax.cs文件移至App_Code文件夹并更新了CodeBehind引用Global.asax