在上一章中主要和大家分享了在ASP.NET Core中如何使用Autofac替换自带DI进行构造函数的批量依赖注入,本章将和大家继续分享如何使之能够同时支持属性的批量依赖注入。

约定:

1、仓储层接口都以“I”开头,以“Repository”结尾。仓储层实现都以“Repository”结尾。

2、服务层接口都以“I”开头,以“Service”结尾。服务层实现都以“Service”结尾。

接下来我们正式进入主题,在上一章的基础上我们再添加一个web项目TianYa.DotNetShare.CoreAutofacDemo,首先来看一下我们的解决方案

本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.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("");
var stu2 = StuService.GetStuInfo("");
var stu3 = _stuService.GetStuInfo("");
var stu4 = _stuRepository.GetStuInfo("");
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 = , 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

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

ASP.NET Core Web 应用程序系列(三)- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)的更多相关文章

  1. ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)

    在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...

  2. ASP.NET Core Web 应用程序系列(五)- 在ASP.NET Core中使用AutoMapper进行实体映射

    本章主要简单介绍下在ASP.NET Core中如何使用AutoMapper进行实体映射.在正式进入主题之前我们来看下几个概念: 1.数据库持久化对象PO(Persistent Object):顾名思义 ...

  3. ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)

    在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...

  4. 浅谈.Net Core中使用Autofac替换自带的DI容器

    为什么叫 浅谈 呢?就是字面上的意思,讲得比较浅,又不是不能用(这样是不对的)!!! Aufofac大家都不陌生了,说是.Net生态下最优秀的IOC框架那是一点都过分.用的人多了,使用教程也十分丰富, ...

  5. ASP.NET Core Web 应用程序系列(四)- ASP.NET Core 异步编程之async await

    PS:异步编程的本质就是新开任务线程来处理. 约定:异步的方法名均以Async结尾. 实际上呢,异步编程就是通过Task.Run()来实现的. 了解线程的人都知道,新开一个线程来处理事务这个很常见,但 ...

  6. Asp.Net Core Web应用程序—探索

    前言 作为一个Windows系统下的开发者,我对于Core的使用机会几乎为0,但是考虑到微软的战略规划,我觉得,Core还是有先了解起来的必要. 因为,目前微软已经搞出了两个框架了,一个是Net标准( ...

  7. 使用react全家桶制作博客后台管理系统 网站PWA升级 移动端常见问题处理 循序渐进学.Net Core Web Api开发系列【4】:前端访问WebApi [Abp 源码分析]四、模块配置 [Abp 源码分析]三、依赖注入

    使用react全家桶制作博客后台管理系统   前面的话 笔者在做一个完整的博客上线项目,包括前台.后台.后端接口和服务器配置.本文将详细介绍使用react全家桶制作的博客后台管理系统 概述 该项目是基 ...

  8. Azure Service Bus(三)在 .NET Core Web 应用程序发送ServiceBus Queue

    一,引言 在之前上一篇讲解到 Azure ServiceBus Queue 中,我们实地的演示了在控制台中如何操作ServiceBus Queue ,使用 Azure.Messgae.Service ...

  9. ASP.NET Core Web 应用程序开发期间部署到IIS自定义主机域名并附加到进程调试

    想必大家之前在进行ASP.NET Web 应用程序开发期间都有用到过将我们的网站部署到IIS自定义主机域名并附加到进程进行调试. 那我们的ASP.NET Core Web 应用程序又是如何部署到我们的 ...

随机推荐

  1. CQRS+ES项目解析-Diary.CQRS

    在<当我们在讨论CQRS时,我们在讨论些神马>中,我们讨论了当使用CQRS的过程中,需要关心的一些问题.其中与CQRS关联最为紧密的模式莫过于Event Sourcing了,CQRS与ES ...

  2. 终极CURD-4-java8新特性

    目录 1 概述 2 lambda表达式 2.1 lambda重要知识点总结 2.2 java内置函数接口 2.3 方法引用 2.4 构造器引用 2.5 数组引用 2.6 lambda表达式的陷阱 3 ...

  3. Winform中实现将照片剪贴到系统剪切板中(附代码下载)

    场景 效果 点击剪切按钮 点击粘贴按钮 注: 博客主页: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免 ...

  4. 手摸手教你编写你人生中第一个HTML页面

    本文是<HTML5与CSS3基础语法自学教程>的第二篇,首发于[前端课湛]微信公众号. 导读:本小节主要讲解 HTML 的基础语法内容,将通过编写第一个 HTML 页面来学习 HTML 的 ...

  5. RMAN 下NOARCHIVELOG和ARCHIVE模式的恢复

    恢复处于NOARCHIVELOG模式的数据库 当数据库处于NOARCHIVELOG模式时,如果出现介质故障 ,则最后一次备份之后对数据库所做的任何操作都将丢失.通过RMAN执行恢复时,只需要执行res ...

  6. Shell(五):函数

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用. shell中函数的定义格式: [ function ] funname [()] { action; [return i ...

  7. 菜鸟刷面试题(四、Spring/Spring MVC/Spring Boot/Spring Cloud篇)

    目录: 为什么要使用 spring? 解释一下什么是 aop? 解释一下什么是 ioc? spring 有哪些主要模块? spring 常用的注入方式有哪些? spring 中的 bean 是线程安全 ...

  8. 【30天自制操作系统】day04:C语言与目前执行流程图

    用 C 语言直接写入内存 原来依靠汇编 void io_hlt(void); void write_mem8(int addr, int data); void HariMain(void){ int ...

  9. 使用vue脚手架快速创建vue项目(入门)

    1.安装环境 为了方便,以下操作大多数中命令行中运行,window可以用cmd,powershell,gitbash等. 安装node.js 打开它的官网,或者中文网站,然后直接下载就可以了,然后跟安 ...

  10. 线程提供的方法:static void sleep(long ms),会进入阻塞状态,休眠

    package seday08.thread; import java.util.Scanner; /*** @author xingsir * 线程提供的方法:static void sleep(l ...