任务21 :了解ASP.NET Core 依赖注入,看这篇就够了
一、什么是依赖注入
- 1.1 依赖
- 1.2 什么注入
- 为什么反转
- 何为容器
二、.NET Core DI
- 2.1 实例的注册
- 2.2 实例生命周期之单例
- 2.3 实例生命周期之Tranisent
- 2.4 实例生命周期之Scoped
三、DI在ASP.NET Core中的应用
- 3.1 在Startup类中初始化
- 3.2 Controller中使用
- 3.3 View中使用
- 3.4 通过HttpContext来获取
四、如何替换其它的Ioc容器
一、什么是依赖注入(Denpendency Injection)
1.1依赖

1.2 什么是注入
private ILoginService<ApplicationUser> _loginService;
public AccountController()
{
_loginService = new EFLoginService()
}
大师说,这样不好。你不应该自己创建它,而是应该由你的调用者给你。于是你通过构造函数让外界把这两个依赖传给你。
public
AccountController(ILoginService<ApplicationUser> loginService)
{
_loginService = loginService;
}
把依赖的创建丢给其它人,自己只负责使用,其它人丢给你依赖的这个过程理解为注入。
1.3 为什么要反转?

var controller = new AccountController(new EFLoginService());
controller.Login(userName, password);
// 用Redis来替换原来的EF登录
var controller = new AccountController(new RedisLoginService());
controller.Login(userName, password);
1.4 何为容器
- 绑定服务与实例之间的关系
- 获取实例,并对实例进行管理(创建与销毁)

二、.NET Core DI
2.1 实例的注册
- IServiceCollection 负责注册
- IServiceProvider 负责提供实例
var serviceCollection = new ServiceCollection()
.AddTransient<ILoginService, EFLoginService>()
.AddSingleton<ILoginService, EFLoginService>()
.AddScoped<ILoginService, EFLoginService>();
public interface IServiceCollection : IList<ServiceDescriptor>
{
}
我们上面的AddTransient、AddSignletone和Scoped方法是IServiceCollection的扩展方法, 都是往这个List里面添加ServiceDescriptor。
private static IServiceCollection Add(
IServiceCollection collection,
Type serviceType,
Type implementationType,
ServiceLifetime lifetime)
{
var descriptor =
new ServiceDescriptor(serviceType, implementationType, lifetime);
collection.Add(descriptor);
return collection;
}
2.2 实例的生命周期之单例
- Transient: 每一次GetService都会创建一个新的实例
- Scoped: 在同一个Scope内只初始化一个实例 ,可以理解为( 每一个request级别只创建一个实例,同一个http request会在一个 scope内)
- Singleton :整个应用程序生命周期以内只创建一个实例
public enum ServiceLifetime
{
Singleton,
Scoped,
Transient
}
public interface IOperation
{
Guid OperationId { get; }
}
public interface IOperationSingleton : IOperation { }
public interface IOperationTransient : IOperation{}
public interface IOperationScoped : IOperation{}
我们的 Operation实现很简单,可以在构造函数中传入一个Guid进行赋值,如果没有的话则自已New一个 Guid。
public class Operation :
IOperationSingleton,
IOperationTransient,
IOperationScoped
{
private Guid _guid;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Operation</span><span class="hljs-params">()</span> </span>{
_guid = Guid.NewGuid();
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Operation</span><span class="hljs-params">(Guid guid)</span>
</span>{
_guid = guid;
}
<span class="hljs-keyword">public</span> Guid OperationId => _guid;
}
在程序内我们可以多次调用ServiceProvider的GetService方法,获取到的都是同一个实例。
var services = new ServiceCollection();
// 默认构造
services.AddSingleton<IOperationSingleton, Operation>();
// 自定义传入Guid空值
services.AddSingleton<IOperationSingleton>(
new Operation(Guid.Empty));
// 自定义传入一个New的Guid
services.AddSingleton <IOperationSingleton>(
new Operation(Guid.NewGuid()));
var provider = services.BuildServiceProvider();
// 输出singletone1的Guid
var singletone1 = provider.GetService<IOperationSingleton>();
Console.WriteLine($"signletone1: {singletone1.OperationId}");
// 输出singletone2的Guid
var singletone2 = provider.GetService<IOperationSingleton>();
Console.WriteLine(\(<span class="hljs-string">"signletone2: {singletone2.OperationId}"</span>);
Console.WriteLine(\)"singletone1 == singletone2 ? : { singletone1 == singletone2 }");
我们对IOperationSingleton注册了三次,最后获取两次,大家要注意到我们获取到的始终都是我们最后一次注册的那个给了一个Guid的实例,前面的会被覆盖。
2.3 实例生命周期之Tranisent
这次我们获取到的IOperationTransient为两个不同的实例。
var services = new ServiceCollection();
services.AddTransient<IOperationTransient, Operation>();
var provider = services.BuildServiceProvider();
var transient1 = provider.GetService<IOperationTransient>();
Console.WriteLine($"transient1: {transient1.OperationId}");
var transient2 = provider.GetService<IOperationTransient>();
Console.WriteLine(\(<span class="hljs-string">"transient2: {transient2.OperationId}"</span>);
Console.WriteLine(\)"transient1 == transient2 ? :
{ transient1 == transient2 }");

2.4 实例生命周期之Scoped
var services = new ServiceCollection()
.AddScoped<IOperationScoped, Operation>()
.AddTransient<IOperationTransient, Operation>()
.AddSingleton<IOperationSingleton, Operation>();
接下来我们用ServiceProvider.CreateScope方法创建一个Scope
var provider = services.BuildServiceProvider();
using (var scope1 = provider.CreateScope())
{
var p = scope1.ServiceProvider;
<span class="hljs-keyword">var</span> scopeobj1 = p.GetService<IOperationScoped>();
<span class="hljs-keyword">var</span> transient1 = p.GetService<IOperationTransient>();
<span class="hljs-keyword">var</span> singleton1 = p.GetService<IOperationSingleton>();
<span class="hljs-keyword">var</span> scopeobj2 = p.GetService<IOperationScoped>();
<span class="hljs-keyword">var</span> transient2 = p.GetService<IOperationTransient>();
<span class="hljs-keyword">var</span> singleton2 = p.GetService<IOperationSingleton>();
Console.WriteLine(
$<span class="hljs-string">"scope1: { scopeobj1.OperationId },"</span> +
$<span class="hljs-string">"transient1: {transient1.OperationId}, "</span> +
$<span class="hljs-string">"singleton1: {singleton1.OperationId}"</span>);
Console.WriteLine($<span class="hljs-string">"scope2: { scopeobj2.OperationId }, "</span> +
$<span class="hljs-string">"transient2: {transient2.OperationId}, "</span> +
$<span class="hljs-string">"singleton2: {singleton2.OperationId}"</span>);
}
接下来
scope1: 200d1e63-d024-4cd3-88c9-35fdf5c00956,
transient1: fb35f570-713e-43fc-854c-972eed2fae52,
singleton1: da6cf60f-670a-4a86-8fd6-01b635f74225
scope2: 200d1e63-d024-4cd3-88c9-35fdf5c00956,
transient2: 2766a1ee-766f-4116-8a48-3e569de54259,
singleton2: da6cf60f-670a-4a86-8fd6-01b635f74225
如果再创建一个新的Scope运行,
scope1: 29f127a7-baf5-4ab0-b264-fcced11d0729,
transient1: 035d8bfc-c516-44a7-94a5-3720bd39ce57,
singleton1: da6cf60f-670a-4a86-8fd6-01b635f74225
scope2: 29f127a7-baf5-4ab0-b264-fcced11d0729,
transient2: 74c37151-6497-4223-b558-a4ffc1897d57,
singleton2: da6cf60f-670a-4a86-8fd6-01b635f74225

三、DI在ASP.NET Core中的应用
3.1在Startup类中初始化
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ILoginService<ApplicationUser>,
EFLoginService>();
services.AddMvc();
)
ASP.NET Core的一些组件已经提供了一些实例的绑定,像AddMvc就是Mvc Middleware在 IServiceCollection上添加的扩展方法。
public static IMvcBuilder AddMvc(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
<span class="hljs-keyword">var</span> builder = services.AddMvcCore();
builder.AddApiExplorer();
builder.AddAuthorization();
AddDefaultFrameworkParts(builder.PartManager);
...
}
3.2 Controller中使用
private ILoginService<ApplicationUser> _loginService;
public AccountController(
ILoginService<ApplicationUser> loginService)
{
_loginService = loginService;
}
我们只要在控制器的构造函数里面写了这个参数,ServiceProvider就会帮我们注入进来。这一步是在Mvc初始化控制器的时候完成的,我们后面再介绍到Mvc的时候会往细里讲。
3.3 View中使用
@using MilkStone.Services;
@model MilkStone.Models.AccountViewModel.LoginViewModel
@inject ILoginService<ApplicationUser> loginService
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
@loginService.GetUserName()
</body>
</html>
3.4 通过 HttpContext来获取实例
HttpContext.RequestServices.GetService<ILoginService<ApplicationUser>>();
四、如何替换其它的Ioc容器
builder.RegisterGeneric(typeof(LoggingBehavior<,>)).As(typeof(IPipelineBehavior<,>));
builder.RegisterGeneric(typeof(ValidatorBehavior<,>)).As(typeof(IPipelineBehavior<,>));
这会给我们的初始化带来一些便利性,我们来看看如何替换Autofac到ASP.NET Core。我们只需要把Startup类里面的 ConfigureService的 返回值从 void改为 IServiceProvider即可。而返回的则是一个AutoServiceProvider。
public IServiceProvider ConfigureServices(
IServiceCollection services){
services.AddMvc();
// Add other framework services
<span class="hljs-comment">// Add Autofac</span>
<span class="hljs-keyword">var</span> containerBuilder = <span class="hljs-keyword">new</span> ContainerBuilder();
containerBuilder.RegisterModule<DefaultModule>();
containerBuilder.Populate(services);
<span class="hljs-keyword">var</span> container = containerBuilder.Build();
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> AutofacServiceProvider(container);
}
4.1 有何变化

<div class="section section-blog-info">
<div class="row">
<div class="col-md-6">
<div class="entry-categories">分类: <span class="label label-primary"><a href="http://www.jessetalk.cn/category/tech/">技术随笔</a></span> </div>
<div class="entry-tags">标签:<span class="entry-tag"><a href="http://www.jessetalk.cn/tag/asp-net-core/" rel="tag">asp.net core</a></span><span class="entry-tag"><a href="http://www.jessetalk.cn/tag/di/" rel="tag">DI</a></span></div> </div>
<div class="col-md-6">
<div class="entry-social">
<a target="_blank" rel="tooltip" data-original-title="分享到 Facebook" class="btn btn-just-icon btn-round btn-facebook" href="https://www.facebook.com/sharer.php?u=http://www.jessetalk.cn/2017/11/06/di-in-aspnetcore/">
<i class="fa fa-facebook"></i>
</a>
<a target="_blank" rel="tooltip" data-original-title="分享至微博" class="btn btn-just-icon btn-round btn-twitter" href="http://twitter.com/share?url=http://www.jessetalk.cn/2017/11/06/di-in-aspnetcore/&text=%E4%BA%86%E8%A7%A3ASP.NET%20Core%20%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5%EF%BC%8C%E7%9C%8B%E8%BF%99%E7%AF%87%E5%B0%B1%E5%A4%9F%E4%BA%86">
<i class="fa fa-twitter"></i>
</a>
<a rel="tooltip" data-original-title=" Share on Email" class="btn btn-just-icon btn-round" href="mailto:?subject=了解ASP.NET%20Core%20依赖注入,看这篇就够了&body=http://www.jessetalk.cn/2017/11/06/di-in-aspnetcore/">
<i class="fa fa-envelope"></i>
</a>
</div>
</div> </div>
<hr>
任务21 :了解ASP.NET Core 依赖注入,看这篇就够了的更多相关文章
- # ASP.NET Core依赖注入解读&使用Autofac替代实现
标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...
- 实现BUG自动检测 - ASP.NET Core依赖注入
我个人比较懒,能自动做的事绝不手动做,最近在用ASP.NET Core写一个项目,过程中会积累一些方便的工具类或框架,分享出来欢迎大家点评. 如果以后有时间的话,我打算写一个系列的[实现BUG自动检测 ...
- [译]ASP.NET Core依赖注入深入讨论
原文链接:ASP.NET Core Dependency Injection Deep Dive - Joonas W's blog 这篇文章我们来深入探讨ASP.NET Core.MVC Core中 ...
- asp.net core 依赖注入几种常见情况
先读一篇注入入门 全面理解 ASP.NET Core 依赖注入, 学习一下基本使用 然后学习一招, 不使用接口规范, 直接写功能类, 一般情况下可以用来做单例. 参考https://www.cnblo ...
- ASP.NET Core依赖注入——依赖注入最佳实践
在这篇文章中,我们将深入研究.NET Core和ASP.NET Core MVC中的依赖注入,将介绍几乎所有可能的选项,依赖注入是ASP.Net Core的核心,我将分享在ASP.Net Core应用 ...
- 自动化CodeReview - ASP.NET Core依赖注入
自动化CodeReview系列目录 自动化CodeReview - ASP.NET Core依赖注入 自动化CodeReview - ASP.NET Core请求参数验证 我个人比较懒,能自动做的事绝 ...
- ASP.NET Core 依赖注入最佳实践——提示与技巧
在这篇文章,我将分享一些在ASP.NET Core程序中使用依赖注入的个人经验和建议.这些原则背后的动机如下: 高效地设计服务和它们的依赖. 预防多线程问题. 预防内存泄漏. 预防潜在的BUG. 这篇 ...
- ASP.NET Core依赖注入最佳实践,提示&技巧
分享翻译一篇Abp框架作者(Halil İbrahim Kalkan)关于ASP.NET Core依赖注入的博文. 在本文中,我将分享我在ASP.NET Core应用程序中使用依赖注入的经验和建议. ...
- ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】
ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Autofac实现和自定义实现扩展方法 3.1 安装Autof ...
- ASP.NET Core 依赖注入基本用法
ASP.NET Core 依赖注入 ASP.NET Core从框架层对依赖注入提供支持.也就是说,如果你不了解依赖注入,将很难适应 ASP.NET Core的开发模式.本文将介绍依赖注入的基本概念,并 ...
随机推荐
- PyCharm使用技巧总结
PyCharm高频使用快捷键 快速修复:ALT + ENTER 搜索: 双击Shif 垂直分隔窗口: ALT + V 另起一行: SHIFT + ENTER 删除当前插入符所在的行: Ctrl + Y ...
- java调用sqlldr报错:Message 2100 not found
java调用Oracle的sqlldr命令报错:Message 2100 not found; No message file for product=RDBMS, facility=ULMessag ...
- Maven生成可以直接运行的jar包的多种方式(转)
转自:https://blog.csdn.net/xiao__gui/article/details/47341385 Maven可以使用mvn package指令对项目进行打包,如果使用java - ...
- 【改】utf-8 的去掉BOM的方法
最近在测试中发现,linux系统中导出的文件,有记事本打开另存为或者保存后,再次导入进linux系统,发现失败了,对比文件内容,没发现区别,打开二进制文件对比发现,文件头部多了三个字符:EF BB B ...
- mysql查询每个部门/班级前几名
Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id . +----+-------+--------+--------------+ | I ...
- python笔记(1)--基础知识
一.注释 单行注释 #打印“hello world” print("hello.world!") 另外一种单行注释 print("hello,world!") ...
- mysql数据精度丢失问题深入探讨
不要盲目的说float和double精度可能发生丢失,而是说在存取时因为精度不一致会发生丢失,当然这里的丢失指的是扩展或者截断了,丢失了原有的精度.decimal是好,但不是说不会发生任何精度丢失.如 ...
- maven 配置发布仓库
·首先,在工程的pom.xml中添加仓库信息 <distributionManagement> <repository> <id>releases</id&g ...
- web css
CSS圆角——透明圆角化背景图片 序言:第一章中我介绍了最基本的纯CSS圆角框的实现原理,并给出Demo,在本章中会对上一个模型作一些新的创新,实现将背景图片透明圆角化.并给出一些漂亮的通用演示效果. ...
- 和风api爬取天气预报数据
''' 和风api爬取天气预报数据 目标:https://free-api.heweather.net/s6/weather/forecast?key=cc33b9a52d6e48de85247779 ...