天天看點

asp.net AutoFac 自動注入

在我這個架構中需要引用一下幾個dll:

Autofac,Autofac.Configuration,Autofac.Mvc4,Autofac.WebApi

配置方面我用的是XML檔案配置,

在添加完引用之後,就可以配置了!下面是配置代碼! 首先要弄清楚,整個MyautoFac.Web的程式入口Global.asax.cs檔案中的Application_Start()方法裡

 public class MvcApplication : System.Web.HttpApplication

    {

        protected void Application_Start()

        {

            AutofacRegister.Register();//正常注入 -------》App_Start 檔案夾下

         }

    }

App_Start 檔案夾下 代碼如下

using System;

using System.Collections.Generic;

using System.Linq;

using System.Reflection;

using System.Web;

using System.Web.Mvc;

using Autofac;

using Autofac.Configuration;

using Autofac.Integration.Mvc;

namespace SupervisionWin.Web

{

    public class AutofacRegister

    {

        public static void Register()

        {

            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));

            builder.RegisterSource(new ViewRegistrationSource());//頁面注入

            builder.RegisterFilterProvider();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

        }

    }

}

XML 配置

 然後在Web.config裡填代碼!如下:

        <configSections>

           <!--注冊autofac節點,在此之前需要引入Autofac.Configuration-->

           <section name="autofac"type="Autofac.Configuration.SectionHandler,Autofac.Configuration"/> 

        </configSections>

         <!--autofac節點的屬性設定-->

         <autofac>

           <!--這個部分之前我嘗試過直接注入,可是後來發現一個問題就是,有時候不會被識别,是以我嘗試分别注入每個類庫,其中name屬性是相對路徑-->

           <files>

             <!--關于section屬性,是檔案中的autoFac節點-->

             <file name="..//MyAutoFac.Service/Configuration.config"section="autoFac"></file>

             <filename="..//MyAutoFac.Repository/Configuration.config"section="autoFac"></file>

           </files>

          </autofac>

      至于Configuration.config檔案,我隻舉一個例子說明!單獨建立一個

       <configSections>

         <section name="autoFac"type="Autofac.Configuration.SectionHandler,Autofac.Configuration"/>

       </configSections>

        <!--defaultAssemby屬性是非必須屬性,但是我喜歡把它加上,為了防止出錯-->

        <autoFacdefaultAssembly="MyAutoFac.Service">

          <!--這個component節點就是依賴注入的配置部分 type屬性是MyAutoFac.Service中的User檔案還有命名空間-->

         <components>

            <!--之後的service屬性是指的MyAutoFac.Service.IService.UserService檔案-->

           <componenttype="MyAutoFac.Service.UserService, MyAutoFac.Service" service="MyAutoFac.Service.IService.IUserService"/>

         </components>

        </autoFac>  

轉載于:https://blog.51cto.com/jaycheer520/1628049