ASP.NET Core Web Application Series (c) - Use in ASP.NET Core replacement Autofac DI comes constructors and properties for batch dependency injection (MVC among applications)

Original: ASP.NET Core series the Web application (c) - Use in ASP.NET Core Autofac DI comes replacement for constructors and properties of bulk dependency injection (MVC among applications)

In the last chapter is mainly to share how to use Autofac be replaced comes DI constructor dependency injection quantities in ASP.NET Core, the chapter will continue to share with everyone how to enable it to support both batch attribute dependency injection.

Conventions:

1, storage layer interfaces with "I" beginning to "Repository" at the end. Storage layer implementations to "Repository" at the end.

2, the service layer interfaces with "I" beginning to "Service" at the end. Service layer to achieve both "Service" at the end.

Next we officially entered the theme, based on the previous chapter we add a web project TianYa.DotNetShare.CoreAutofacDemo, first look at our solutions

 

This demo web projects for the MVC framework ASP.NET Core Web Application (.NET Core 2.2), you need to reference the following assemblies:

1, TianYa.DotNetShare.Model our physical layer

2, TianYa.DotNetShare.Service our services layer

3, TianYa.DotNetShare.Repository our warehouse layer, normal web project we should not be using the storage layer, we quote here is to demonstrate the IOC dependency injection

4, Autofac dependency injection base component

5, Autofac.Extensions.DependencyInjection dependency injection auxiliary components of .NET Core

Which Autofac and Autofac.Extensions.DependencyInjection need references from our NuGet, Click to download the following two packages:

接着我们在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.CoreAutofacDemo
{
    /// <summary>
    /// 注册Autofac模块
    /// </summary>
    public class AutofacModuleRegister : Autofac.Module
    {
        /// <summary>
        /// 重写Autofac管道Load方法,在这里注册注入
        /// </summary>
        protected override void Load(ContainerBuilder builder)
        {
            //builder.RegisterType<StudentRepository>().As<IStudentRepository>().PropertiesAutowired()
            //    .InstancePerLifetimeScope();
            //builder.RegisterType<StudentService>().As<IStudentService>().PropertiesAutowired()
            //    .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Repository"))
                .Where(a => a.Name.EndsWith("Repository"))
                .AsSelf().AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(GetAssemblyByName("TianYa.DotNetShare.Service"))
                .Where(a => a.Name.EndsWith("Service"))
                .AsSelf().AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();

            //注册MVC控制器,注册所有到控制器
            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
                .Where(type => typeof(Microsoft.AspNetCore.Mvc.ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
        }

        /// <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.CoreAutofacDemo
{
    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).AddControllersAsServices();

            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:

1、需要将自带的ConfigureServices方法的返回值改成IServiceProvider。

2、需要修改如下语句:

将原有的:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

改为:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddControllersAsServices();

接下来我们来看看控制器里面怎么弄:

复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using TianYa.DotNetShare.CoreAutofacDemo.Models;

using TianYa.DotNetShare.Service;
using TianYa.DotNetShare.Repository;
using TianYa.DotNetShare.Repository.Impl;

namespace TianYa.DotNetShare.CoreAutofacDemo.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 定义仓储层学生抽象类对象
        /// </summary>
        private IStudentRepository _stuRepository;

        /// <summary>
        /// 定义服务层学生抽象类对象
        /// </summary>
        private IStudentService _stuService;

        /// <summary>
        /// 定义服务层学生抽象类对象
        /// 属性注入:访问修饰符必须为public,否则会注入失败。
        /// </summary>
        public IStudentService StuService { get; set; }

        /// <summary>
        /// 定义仓储层学生实现类对象
        /// 属性注入:访问修饰符必须为public,否则会注入失败。
        /// </summary>
        public StudentRepository StuRepository { get; set; }

        /// <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");
            var stu3 = _stuService.GetStuInfo("10002");
            var stu4 = _stuRepository.GetStuInfo("1003");
            string msg = $"学号:10000,姓名:{stu1.Name},性别:{stu1.Sex},年龄:{stu1.Age}<br />";
            msg += $"学号:10001,姓名:{stu2.Name},性别:{stu2.Sex},年龄:{stu2.Age}<br/>";
            msg += $"学号:10002,姓名:{stu3.Name},性别:{stu3.Sex},年龄:{stu3.Age}<br/>";
            msg += $"学号:10003,姓名:{stu4.Name},性别:{stu4.Sex},年龄:{stu4.Age}<br/>";

            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/11RM9jUr9n342TmV8z8MEHA 
提取码:86s0

 

版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12154058.html