.net core中使用autofac


.net core2.1 三層中使用Autofac代替原來Ioc

  首先,現有的三層項目的結構

其中  Repository

 public interface IPersonRepository
    {
         string Eat();
    }
復制代碼
public class PersonRepository : IPersonRepository
    {
        public string Eat()
        {
            return "吃飯";
        }
    }
復制代碼

 Service

public interface IPersonService
    {
        string Eat();
    }
復制代碼
 public class PersonService : IPersonService
    {
       private  IPersonRepository _personRespository;
        //通過構造函數注入 repository
        public  PersonService(IPersonRepository personRespository)
        {
          _personRespository = personRespository;
        }
        public string Eat()
        {
            return  _personRespository.Eat();
        }
    }
復制代碼

 

一、安裝Autofac

      nuget上安裝Autofac

 

二、替換內置的DI框架

    將Startup.cs中的ConfigureServices返回類型改為IServiceProvider,然后新起一個方法RegisterAutofac把創建容器的代碼放到其中,然后建一個AutofacModuleRegister類繼承Autofac的Module,然后重寫Module的Load方法 來存放新組件的注入代碼,避免Startup.cs文件代碼過多混亂。

    

復制代碼
 public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            return RegisterAutofac(services);//注冊Autofac
        }
復制代碼
復制代碼
 private IServiceProvider RegisterAutofac(IServiceCollection services)
        {
            //實例化Autofac容器
            var builder = new ContainerBuilder();
            //將Services中的服務填充到Autofac中
            builder.Populate(services);
            //新模塊組件注冊    
            builder.RegisterModule<AutofacModuleRegister>();
            //創建容器
            var Container = builder.Build();
            //第三方IOC接管 core內置DI容器 
            return new AutofacServiceProvider(Container);
        }
復制代碼
復制代碼
 public class AutofacModuleRegister:Autofac.Module
    {
        //重寫Autofac管道Load方法,在這里注冊注入
        protected override void Load(ContainerBuilder builder)
        {
            //注冊Service中的對象,Service中的類要以Service結尾,否則注冊失敗
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
            //注冊Repository中的對象,Repository中的類要以Repository結尾,否則注冊失敗
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();           
        }
        /// <summary>
        /// 根據程序集名稱獲取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名稱</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }
    }
復制代碼

 

此時Autofac基本使用已經配好了。

三、測試效果

        修改HomeController 實現注入Service

復制代碼
 public class HomeController : Controller
    {
        private IPersonService _personService;
      
        //通過構造函數注入Service
        public HomeController(IPersonService personService)
        {
            _personService = personService;
        }
        public IActionResult Index()
        {
            ViewBag.eat = _personService.Eat();
            return View();
        }
}
復制代碼

頁面結果:

四、一個接口多個實現的情況

   比喻我現在在Service 中建三個類,IPayService, WxPayService,AliPayService,其中WxPayService,AliPayService都實現接口IPayService。

 public interface IPayService
    {
        string Pay();
    }
復制代碼
public class AliPayService : IPayService
    {
        public string Pay()
        {
            return "支付寶支付";
        }
    }
復制代碼
復制代碼
 public class WxPayService : IPayService
    {
        public string Pay()
        {
            return "微信支付";
        }
    }
復制代碼

  先試一下結果,修改HomeController

復制代碼
 public class HomeController : Controller
    {
        private IPersonService _personService;
        private IPayService _payService;
      
        //通過構造函數注入Service
        public HomeController(IPersonService personService,IPayService payService)
        {
            _personService = personService;
            _payService = payService;
        }
        public IActionResult Index()
        {
            ViewBag.eat = _personService.Eat();
            ViewBag.pay = _payService.Pay();
            return View();
        }
    }
復制代碼

  View

@{
    ViewData["Title"] = "Home Page";
}
@ViewBag.eat <br />
@ViewBag.pay

輸出頁面:

    最后得到的是微信支付,因為兩個對象實現一個接口的時候,注冊時后面注冊的會覆蓋前面注冊的。如果我想得到支付寶支付要怎么做呢?

 我們可以用另外一種注冊方式RegisterType,修改注冊方式AutofacModuleRegister.cs。

 

復制代碼
 public class AutofacModuleRegister:Autofac.Module
    {
        //重寫Autofac管道Load方法,在這里注冊注入
        protected override void Load(ContainerBuilder builder)
        {
            //注冊Service中的對象,Service中的類要以Service結尾,否則注冊失敗
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
            //注冊Repository中的對象,Repository中的類要以Repository結尾,否則注冊失敗
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();
            //單獨注冊
            builder.RegisterType<WxPayService>().Named<IPayService>(typeof(WxPayService).Name);
            builder.RegisterType<AliPayService>().Named<IPayService>(typeof(AliPayService).Name);
        }
        /// <summary>
        /// 根據程序集名稱獲取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名稱</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }
    }
復制代碼

 

用Named區分兩個組件的不同,后面的typeof(WxPayService).Name 是任意字符串,這里直接用這個類名作標識,方便取出來時也是用這個名字,不易忘記。

然后就是取出對應的組件了,取的時候用Autofac的 上下文(IComponentContext) ,修改HomeController

復制代碼
 public class HomeController : Controller
    {
        private IPersonService _personService;
        private IPayService _wxPayService;
        private IPayService _aliPayService;
        private IComponentContext _componentContext;//Autofac上下文
        //通過構造函數注入Service
        public HomeController(IPersonService personService, IComponentContext componentContext)
        {
            _personService = personService;
            _componentContext = componentContext;
            //解釋組件
            _wxPayService = _componentContext.ResolveNamed<IPayService>(typeof(WxPayService).Name);
            _aliPayService =_componentContext.ResolveNamed<IPayService>(typeof(AliPayService).Name);
        }
        public IActionResult Index()
        {
            ViewBag.eat = _personService.Eat();
            ViewBag.wxPay = _wxPayService.Pay();
            ViewBag.aliPay = _aliPayService.Pay();
            return View();
        }
    }
復制代碼

 Index View:

@{
    ViewData["Title"] = "Home Page";
}
@ViewBag.eat <br />
@ViewBag.wxPay <br />
@ViewBag.aliPay

結果:

 

完成。

轉自https://www.cnblogs.com/wei325/p/9191686.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM