在上一章中主要和大家分享在MVC當中如何使用ASP.NET Core內置的DI進行批量依賴注入,本章將繼續和大家分享在ASP.NET Core中如何使用Autofac替換自帶DI進行批量依賴注入。
PS:本章將主要采用構造函數注入的方式,下一章將繼續分享如何使之能夠同時支持屬性注入的方式。
約定:
1、倉儲層接口都以“I”開頭,以“Repository”結尾。倉儲層實現都以“Repository”結尾。
2、服務層接口都以“I”開頭,以“Service”結尾。服務層實現都以“Service”結尾。
接下來我們正式進入主題,在上一章的基礎上我們再添加一個web項目TianYa.DotNetShare.CoreAutofacMvcDemo,首先來看一下我們的解決方案
本demo的web項目為ASP.NET Core Web 應用程序(.NET Core 2.2) MVC框架,需要引用以下幾個程序集:
1、TianYa.DotNetShare.Model 我們的實體層
2、TianYa.DotNetShare.Service 我們的服務層
3、TianYa.DotNetShare.Repository 我們的倉儲層,正常我們的web項目是不應該使用倉儲層的,此處我們引用是為了演示IOC依賴注入
4、Autofac 依賴注入基礎組件
5、Autofac.Extensions.DependencyInjection 依賴注入.NET Core的輔助組件
其中Autofac和Autofac.Extensions.DependencyInjection需要從我們的NuGet上引用,依次點擊下載以下2個包:
接著我們在web項目中添加一個類AutofacModuleRegister.cs用來注冊Autofac模塊,如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks;using Autofac;namespace TianYa.DotNetShare.CoreAutofacMvcDemo {/// <summary>/// 注冊Autofac模塊/// </summary>public class AutofacModuleRegister : Autofac.Module{/// <summary>/// 重寫Autofac管道Load方法,在這里注冊注入/// </summary>protected override void Load(ContainerBuilder builder){builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();//注冊MVC控制器(注冊所有到控制器,控制器注入,就是需要在控制器的構造函數中接收對象)builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.CoreAutofacMvcDemo")).Where(a => a.Name.EndsWith("Controller")).AsImplementedInterfaces();}/// <summary>/// 根據程序集名稱獲取程序集/// </summary>/// <param name="assemblyName">程序集名稱</param>public static Assembly GetAssemblyByName(string assemblyName){return Assembly.Load(assemblyName);}} }
然后打開我們的Startup.cs文件進行注入工作,如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection;using Autofac; using Autofac.Extensions.DependencyInjection;namespace TianYa.DotNetShare.CoreAutofacMvcDemo {public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.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_2);return RegisterAutofac(services); //注冊Autofac }// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseCookiePolicy();app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});}/// <summary>/// 注冊Autofac/// </summary>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);}} }
PS:需要將自帶的ConfigureServices方法的返回值改成IServiceProvider
接下來我們來看看控制器里面怎么弄:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TianYa.DotNetShare.CoreAutofacMvcDemo.Models;using TianYa.DotNetShare.Service; using TianYa.DotNetShare.Repository;namespace TianYa.DotNetShare.CoreAutofacMvcDemo.Controllers {public class HomeController : Controller{/// <summary>/// 定義倉儲層學生抽象類對象/// </summary>protected IStudentRepository StuRepository;/// <summary>/// 定義服務層學生抽象類對象/// </summary>protected IStudentService StuService;/// <summary>/// 通過構造函數進行注入/// 注意:參數是抽象類,而非實現類,因為已經在Startup.cs中將實現類映射給了抽象類/// </summary>/// <param name="stuRepository">倉儲層學生抽象類對象</param>/// <param name="stuService">服務層學生抽象類對象</param>public HomeController(IStudentRepository stuRepository, IStudentService stuService){this.StuRepository = stuRepository;this.StuService = stuService;}public IActionResult Index(){var stu1 = StuRepository.GetStuInfo("10000");var stu2 = StuService.GetStuInfo("10001");string msg = $"學號:10000,姓名:{stu1.Name},性別:{stu1.Sex},年齡:{stu1.Age}<br />";msg += $"學號:10001,姓名:{stu2.Name},性別:{stu2.Sex},年齡:{stu2.Age}";return Content(msg, "text/html", System.Text.Encoding.UTF8);}public IActionResult Privacy(){return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}} }
至此完成處理,接下來就是見證奇跡的時刻了,我們來訪問一下/home/index,看看是否能返回學生信息。
可以發現,返回了學生的信息,說明我們注入成功了。
至此,本章就介紹完了,如果你覺得這篇文章對你有所幫助請記得點贊哦,謝謝!!!
demo源碼:
鏈接:https://pan.baidu.com/s/1un6_wgm6w_bMivPPRGzSqw 提取碼:lt80
?
版權聲明:如有雷同純屬巧合,如有侵權請及時聯系本人修改,謝謝!!!