ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】
1. 前言
关于IoC模式(控制反转)和DI技术(依赖注入),我们已经见过很多的探讨,这里就不再赘述了。比如说必看的Martin Fowler《IoC 容器和 Dependency Injection 模式》,相关资料链接都附于文章末尾。其中我非常赞同Artech的说法"控制更多地体现为一种流程的控制",而依赖注入技术让我们的应用程序实现了松散耦合。
ASP.NET Core本身已经集成了一个轻量级的IOC容器,开发者只需要定义好接口后,在Startup.cs的ConfigureServices方法里使用对应生命周期的绑定方法即可,常见方法如下
services.AddTransient<IApplicationService,ApplicationService>
services.AddScoped<IApplicationService,ApplicationService>
services.AddSingleton<IApplicationService,ApplicationService>
对于上述的三种DI注入方式,官方也给出了详细的解释,我来简单翻译一下
- Transient
Transient 服务在每次请求时被创建,它最好被用于轻量级无状态服务(如我们的Repository和ApplicationService服务) - Scoped
Scoped 服务在每次请求时被创建,生命周期横贯整次请求 - Singleton
顾名思义,Singleton(单例)
服务在第一次请求时被创建(或者当我们在ConfigureServices中指定创建某一实例并运行方法),其后的每次请求将沿用已创建服务。如果开发者的应用需要单例服务情景,请设计成允许服务容器来对服务生命周期进行操作,而不是手动实现单例设计模式然后由开发者在自定义类中进行操作。
在这之后,我们便可以将服务通过构造函数注入或者是属性注入的方式注入到Controller,View(通过使用@inject
),甚至是Filter中(以前使用Unity将依赖注入到Filter真是一种痛苦)。话不多说,先来体验一把
Tips:Startup.cs是什么,详见ASP.NET Core 介绍和项目解读
2. ASP.NET Core 中的DI方式
大多项目举例依赖注入的生命周期演示时,都会采取可变Guid来作为返回显示,此次示例也会这样处理。我们先定义一个IGuidAppService接口,里面定义基接口和三种注入模式的接口
public interface IGuidAppService
{
Guid GuidItem();
}
public interface IGuidTransientAppService : IGuidAppService
{
}
public interface IGuidScopedAppService : IGuidAppService
{
}
public interface IGuidSingletonAppService : IGuidAppService
{
}
同样的,在GuidAppService中定义其实现类。这里为了直观显示每次请求的返回值,采取如下代码
public class GuidAppServiceBase : IGuidAppService
{
private readonly Guid _item;
public GuidAppServiceBase()
{
_item = Guid.NewGuid();
}
public Guid GuidItem()
{
return _item;
}
}
public class GuidTransientAppService : GuidAppServiceBase, IGuidTransientAppService
{
}
public class GuidScopedAppService : GuidAppServiceBase, IGuidScopedAppService
{
}
public class GuidSingletonAppService : GuidAppServiceBase, IGuidSingletonAppService
{
}
最后是Controller和View视图的代码
# Controller
public class HomeController : Controller
{
private readonly IGuidTransientAppService _guidTransientAppService; //#构造函数注入
//private IGuidTransientAppService _guidTransientAppService { get; } #属性注入
private readonly IGuidScopedAppService _guidScopedAppService;
private readonly IGuidSingletonAppService _guidSingletonAppService;
public HomeController(IGuidTransientAppService guidTransientAppService,
IGuidScopedAppService guidScopedAppService, IGuidSingletonAppService guidSingletonAppService)
{
_guidTransientAppService = guidTransientAppService;
_guidScopedAppService = guidScopedAppService;
_guidSingletonAppService = guidSingletonAppService;
}
public IActionResult Index()
{
ViewBag.TransientItem = _guidTransientAppService.GuidItem();
ViewBag.ScopedItem = _guidScopedAppService.GuidItem();
ViewBag.SingletonItem = _guidSingletonAppService.GuidItem();
return View();
}
}
# Index View
<div class="row">
<div >
<h2>GuidItem Shows</h2>
<h3>TransientItem: @ViewBag.TransientItem</h3>
<h3>ScopedItem: @ViewBag.ScopedItem</h3>
<h3>SingletonItem: @ViewBag.SingletonItem</h3>
</div>
</div>
之后我们打开两个浏览器,分别刷新数次,也只会发现“TransientItem”和“ScopedItem”的数值不断变化,“SingletonItem”栏的数值是不会有任何变化的,这就体现出单例模式的作用了,示例图如下
但是这好像还不够,要知道我们的Scoped的解读是“生命周期横贯整次请求”,但是现在演示起来和Transient好像没有什么区别(因为两个页面每次浏览器请求仍然是独立的,并不包含于一次中),所以我们采用以下代码来演示下(同一请求源)
# 新建GuidItemPartial.cshtml视图,复制如下代码,使用@inject注入依赖
@using DependencyInjection.IApplicationService
@inject IGuidTransientAppService TransientAppService
@inject IGuidScopedAppService GuidScopedAppServic
@inject IGuidSingletonAppService GuidSingletonAppService
<div class="row">
<div>
<h2>GuidItem Shows</h2>
<h3>TransientItem: @TransientAppService.GuidItem()</h3>
<h3>ScopedItem: @GuidScopedAppServic.GuidItem()</h3>
<h3>SingletonItem: @GuidSingletonAppService.GuidItem()</h3>
</div>
</div>
# 原先的index视图
@{
ViewData["Title"] = "Home Page";
}
@Html.Partial("GuidItemPartial")
@Html.Partial("GuidItemPartial")
依然是 Ctrl+F5 调试运行,可以发现“ScopedItem”在同一请求源中是不会发生变化的,但是“TransientItem”依然不断变化,理论仍然是支持的
3. Autofac实现和自定义实现扩展方法
除了ASP.NETCore自带的IOC容器外,我们还可以使用其他成熟的DI框架,如Autofac,StructureMap等(笔者只用过Unity,Ninject和Castle,Castle也是使用ABP时自带的)。
3.1 安装Autofac
首先在project.json的dependency
节点中加入Autofac.Extensions.DependencyInjection
引用,目前最新版本是4.0.0-rc3-309
3.2 创建容器并注册依赖
在Startup.cs中创建一个public IContainer ApplicationContainer { get; private set; }
对象,并把ConfigureServices
返回类型改为IServiceProvider
,然后复制以下代码进去,也可以实现相关功能
var builder = new ContainerBuilder();
//注意以下写法
builder.RegisterType<GuidTransientAppService>().As<IGuidTransientAppService>();
builder.RegisterType<GuidScopedAppService>().As<IGuidScopedAppService>().InstancePerLifetimeScope();
builder.RegisterType<GuidSingletonAppService>().As<IGuidSingletonAppService>().SingleInstance();
builder.Populate(services);
this.ApplicationContainer = builder.Build();
return new AutofacServiceProvider(this.ApplicationContainer);
值得注意的几点:
- 创建Autofac容器时不要忘了将
ConfigureServices
的返回值修改为IServiceProvider
- 对应ASP.NET Core提及的不同的生命周期,Autofac也定义了对应的扩展方法,如InstancePerLifetimeScope等,默认为Transient模式,包括EntityFramwork等Context也是该种模式
- Autofac Core不支持从View中注入,但是可以和ASP.NET Core自带IOC容器配合使用
- Autofac Core版本和传统的ASP.NET MVC项目版本的区别
4. 参考链接
- IoC 容器和 Dependency Injection 模式
- 控制反转—维基百科
- DependencyInjection-GitHub
- ASP.NET Core中的依赖注入(4): 构造函数的选择与服务生命周期管理
- Dependency Injectionf!
[转载]
ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】的更多相关文章
- # ASP.NET Core依赖注入解读&使用Autofac替代实现
标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...
- NET Core依赖注入解读&使用Autofac替代实现
NET Core依赖注入解读&使用Autofac替代实现 标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. ...
- [译]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 依赖注入 ASP.NET Core从框架层对依赖注入提供支持.也就是说,如果你不了解依赖注入,将很难适应 ASP.NET Core的开发模式.本文将介绍依赖注入的基本概念,并 ...
- 实现BUG自动检测 - ASP.NET Core依赖注入
我个人比较懒,能自动做的事绝不手动做,最近在用ASP.NET Core写一个项目,过程中会积累一些方便的工具类或框架,分享出来欢迎大家点评. 如果以后有时间的话,我打算写一个系列的[实现BUG自动检测 ...
- 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. 这篇 ...
随机推荐
- A charge WIFI point base on airbase-ng+dhcp+lamp+wiwiz
Make wifi as a hot point Make a script echo $0 $1 case $1 in "start") sleep 1 ifconfig wla ...
- webpy使用mysql数据库操作(web.database)
webpy_web.database模块 webpy框架中使用mysql管理数据库有两种方法,一种是使用python里面的MySQLdb模块: import MySQLdb 还有一种就是用webpy自 ...
- npm ERR! fatal: unable to connect to github.com
https://blog.csdn.net/baidu_30809315/article/details/86520093 git config --global url."https:// ...
- COGS1817. [WC2013]糖果公园
1817. [WC2013]糖果公园 ★★★☆ 输入文件:park.in 输出文件:park.out 简单对比时间限制:8 s 内存限制:512 MB [题目描述] Candyland ...
- 使用struts2中默认的拦截器以及自定义拦截器
转自:http://blog.sina.com.cn/s/blog_82f01d350101echs.html 如何使用struts2拦截器,或者自定义拦截器.特别注意,在使用拦截器的时候,在Acti ...
- 九度OJ 1083:特殊乘法 (基础题)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:4114 解决:2809 题目描述: 写个算法,对2个小于1000000000的输入,求结果. 特殊乘法举例:123 * 45 = 1*4 + ...
- JavaScript如何判断非空
JavaScript判断非空的语句一般为: var elvis; if (typeof elvis !== "undefined" && elvis !== nul ...
- Java for LeetCode 096 Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For examp ...
- curl下载安装
curl下载地址 https://curl.haxx.se/download.html 选择windows generic 下的 下载安装 安装完后解压配置系统环境变量 CURL_HOME ...
- Java一致性的实现
一致性 内存模型 每一个线程有一个工作内存和主存独立 工作内存存放主存中变量的值的拷贝 Happen Before 1.程序次序规则:在一个单独的线程中,按照程序代码的执行流顺序,(时 ...