天天看點

ASP.NET Core Web 應用程式系列(二)- 在ASP.NET Core中使用Autofac替換自帶DI進行批量依賴注入(MVC當中應用)

本系列将和大家分享下ASP.NET Core Web 應用程式的一些基礎知識,本章主要簡單介紹下在ASP.NET Core中如何使用Autofac替換自帶DI進行批量依賴注入。

在上一章中主要和大家分享在MVC當中如何使用ASP.NET Core内置的DI進行批量依賴注入,本章将繼續和大家分享在ASP.NET Core中如何使用Autofac替換自帶DI進行批量依賴注入。

PS:本章将主要采用構造函數注入的方式,下一章将繼續分享如何使之能夠同時支援屬性注入的方式。

約定:

1、倉儲層接口都以“I”開頭,以“Repository”結尾。倉儲層實作都以“Repository”結尾。

2、服務層接口都以“I”開頭,以“Service”結尾。服務層實作都以“Service”結尾。

接下來我們正式進入主題,在上一章的基礎上我們再添加一個web項目TianYa.DotNetShare.CoreAutofacMvcDemo,首先來看一下我們的解決方案

ASP.NET Core Web 應用程式系列(二)- 在ASP.NET Core中使用Autofac替換自帶DI進行批量依賴注入(MVC當中應用)

本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個包:

ASP.NET Core Web 應用程式系列(二)- 在ASP.NET Core中使用Autofac替換自帶DI進行批量依賴注入(MVC當中應用)
接着我們在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,看看是否能傳回學生資訊。

ASP.NET Core Web 應用程式系列(二)- 在ASP.NET Core中使用Autofac替換自帶DI進行批量依賴注入(MVC當中應用)

可以發現,傳回了學生的資訊,說明我們注入成功了。

至此,本章就介紹完了,如果你覺得這篇文章對你有所幫助請記得點贊哦,謝謝!!!

demo源碼:

連結:https://pan.baidu.com/s/1un6_wgm6w_bMivPPRGzSqw 
提取碼:lt80      

版權聲明:如有雷同純屬巧合,如有侵權請及時聯系本人修改,謝謝!!!

繼續閱讀