本来简单介绍了Autofac在Asp.Net Web Forms中的应用,后来又添加了mvc、控制台应用程序中使用Autofac,详情请看源码

ASP.NET Web Forms使用Autofac,至少需要一下步骤:

1,引用Autofac程序集。

2,添加Autofac Web Modules 到 Web.config。

3,在Global.asax中实现IContainerProviderAccessor接口。

 

我们创建一个ASP.NET Web Forms项目,命名为WebFormStudy。

添加引用

添加引用的最简单方式就是用NuGet,右击WebFormStudy项目下的References,选择Manage NuGet Packages,如下图:

 Asp.Net Web Forms/MVC/Console App中使用Autofac

在Search Online中输入auto.web字样,Autofac WebForms Intergration 就搜索到了,点击Install。

安装完后,我们就可以在References中看到添加了Autofac.dll和Autofac.Integration.Web.dll,如下图:

 Asp.Net Web Forms/MVC/Console App中使用Autofac

添加ModulesWeb.config

Autofac管理组件的生命周期并且添加依赖注入到Asp.net管道是通过IHttpModule实现的(注:在HttpApplication 初始化过程中,会根据配置文件加载并初始化相应的实现了IHttpModule接口的HttpModule 对象。对于HttpApplication来说,在它处理HTTP 请求的不同阶段会触发不同的事件,而HttpModule 的意义在于通过注册HttpApplication 的相应的事件,将所需的操作注入整个HTTP 请求的处理流程。ASP.NET 的很多功能,比如身份验证、授权、缓存等,都是通过相应的HttpModule 实现的。摘自:Asp.net Mvc4框架揭秘),你需要在web.config中配置这些Modules。

幸运的是,如果通过NuGet添加Autofac程序集,在安装的时候自动在Web.config中配置了相应的Modules,如下图:

 Asp.Net Web Forms/MVC/Console App中使用Autofac

Global.aszx中实现IContainerProviderAccessor接口

依赖注入模块需要HttpApplication实例实现IContainerProviderAccessor接口。一个完整的全局Application类如下所示:

  public class Global : HttpApplication,IContainerProviderAccessor

    {

 

        static IContainerProvider _containerProvider;

 

        public IContainerProvider ContainerProvider

        {

            get { return _containerProvider; }

        }

        void Application_Start(object sender, EventArgs e)

        {

            // Code that runs on application startup

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

 

 

            #region 我们添加的代码

            var builder = new ContainerBuilder();

            //注册将被通过反射创建的组件

            builder.RegisterType<DatabaseManager>();

            builder.RegisterType<OracleDatabase>().As<IDatabase>();

 

            _containerProvider = new ContainerProvider(builder.Build());

            #endregion

        }

    }

DatabaseManager、OracleDatabase等类代码:

 public interface IDatabase
    {
        string Name { get; }

        string Select(string commandText);

        string Insert(string commandText);

        string Update(string commandText);

        string Delete(string commandText);
    }
IDatabase

相关文章:

  • 2019-09-27
  • 2021-08-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-15
  • 2021-06-27
猜你喜欢
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2021-09-15
  • 2018-06-04
  • 2021-12-11
  • 2021-07-24
相关资源
相似解决方案