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>  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章