ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)
在上一章中主要和大家分享在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("");
var stu2 = StuService.GetStuInfo("");
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 = , 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
版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!
ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)的更多相关文章
- ASP.NET Core Web 应用程序系列(三)- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)
在上一章中主要和大家分享了在ASP.NET Core中如何使用Autofac替换自带DI进行构造函数的批量依赖注入,本章将和大家继续分享如何使之能够同时支持属性的批量依赖注入. 约定: 1.仓储层接口 ...
- ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)
在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...
- ASP.NET Core Web 应用程序系列(五)- 在ASP.NET Core中使用AutoMapper进行实体映射
本章主要简单介绍下在ASP.NET Core中如何使用AutoMapper进行实体映射.在正式进入主题之前我们来看下几个概念: 1.数据库持久化对象PO(Persistent Object):顾名思义 ...
- 浅谈.Net Core中使用Autofac替换自带的DI容器
为什么叫 浅谈 呢?就是字面上的意思,讲得比较浅,又不是不能用(这样是不对的)!!! Aufofac大家都不陌生了,说是.Net生态下最优秀的IOC框架那是一点都过分.用的人多了,使用教程也十分丰富, ...
- ASP.NET Core Web 应用程序系列(四)- ASP.NET Core 异步编程之async await
PS:异步编程的本质就是新开任务线程来处理. 约定:异步的方法名均以Async结尾. 实际上呢,异步编程就是通过Task.Run()来实现的. 了解线程的人都知道,新开一个线程来处理事务这个很常见,但 ...
- Asp.Net Core Web应用程序—探索
前言 作为一个Windows系统下的开发者,我对于Core的使用机会几乎为0,但是考虑到微软的战略规划,我觉得,Core还是有先了解起来的必要. 因为,目前微软已经搞出了两个框架了,一个是Net标准( ...
- ASP.NET Core Web 应用程序开发期间部署到IIS自定义主机域名并附加到进程调试
想必大家之前在进行ASP.NET Web 应用程序开发期间都有用到过将我们的网站部署到IIS自定义主机域名并附加到进程进行调试. 那我们的ASP.NET Core Web 应用程序又是如何部署到我们的 ...
- 使用docker部署Asp.net core web应用程序
拉取aspnetcore最新docker镜像 aspnetcore的docker镜像在docker官网是有的,是由微软提供的.它的依赖镜像是microsoft/dotnet.通过访问网址:https: ...
- 循序渐进学.Net Core Web Api开发系列【0】:序言与目录
一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...
随机推荐
- php调用新浪API生成t.cn短网址链接
新浪提供了长链接转为短链接的API,可以把长链接转为 t.cn/xxx 这种格式的短链接. API: http://api.t.sina.com.cn/short_url/shorten.json ( ...
- inux 网络监控分析
一.sar -n:查看网卡流量 -n 参数,他有6个不同的开关:DEV | EDEV | NFS | NFSD | SOCK | ALL .DEV显示网络接口信息,EDEV显示关于网络错误的统计数据, ...
- LICEcap 动画屏幕录制软件
下载地址 https://licecap.en.softonic.com/ LICEcap捕捉屏幕的区域并保存为gif动画或lcf格式 效果请看下面的链接 https://www.cnblogs ...
- flyway 非常坑爹的中文乱码问题
flyway 也真是够了, 动不动乱码,烦死了! 我的 命令是这样的: flyway -driver=com.mysql.jdbc.Driver -user=root -password=12345 ...
- CGI environment variables
- Hyperledger Fabric:最简单的方式测试你的链码
一直以来,写完链码进行测试都要先搭建一个Fabric环境,然后安装链码进行测试,实际上Fabric提供了最为简单的方式可以允许我们对编写的应用链码进行功能测试,不需要搭建一个完整的Fabeic环境.而 ...
- java的各种日志框架
本文是作者原创,版权归作者所有.若要转载,请注明出处.文章中若有错误和疏漏之处,还请各位大佬不吝指出,谢谢大家. java日志框架有很多,这篇文章我们来整理一下各大主流的日志框架, 包括log4j ...
- Spring Boot Security 保护你的程序
Spring Boot Security 本示例要内容 基于角色的权限访问控制 加密.解密 基于Spring Boot Security 权限管理框架保护应用程序 String Security介绍 ...
- Lucene&Solr框架之第三篇
1.SolrCore的配置 a)schma.xml文件 b)配置中文分析器 2.配置业务域和批量索引导入 a)配置业务域 b)批量索引导入 c)Solrj复杂查询(用Query页面复杂查询.用程序实现 ...
- English:Root "tele"
Xx_Introduction tele mean "far" mean"faar" cognate word have tele\culture\tel\pa ...