NET Core依赖注入解读&使用Autofac替代实现

标签: 依赖注入 Autofac ASPNETCore


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);

值得注意的几点:

  1. 创建Autofac容器时不要忘了将ConfigureServices的返回值修改为IServiceProvider
  2. 对应ASP.NET Core提及的不同的生命周期,Autofac也定义了对应的扩展方法,如InstancePerLifetimeScope等,默认为Transient模式,包括EntityFramwork等Context也是该种模式
  3. Autofac Core不支持从View中注入,但是可以和ASP.NET Core自带IOC容器配合使用
  4. Autofac Core版本和传统的ASP.NET MVC项目版本的区别

4. 参考链接

NET Core依赖注入解读&使用Autofac替代实现的更多相关文章

  1. # ASP.NET Core依赖注入解读&使用Autofac替代实现

    标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...

  2. ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】

    ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Autofac实现和自定义实现扩展方法 3.1 安装Autof ...

  3. .net core 依赖注入, autofac 简单使用

    综述 ASP.NET Core  支持依赖注入, 也推荐使用依赖注入. 主要作用是用来降低代码之间的耦合度. 什么是控制反转? 控制反转(Inversion of Control,缩写为IoC),是面 ...

  4. [译]ASP.NET Core依赖注入深入讨论

    原文链接:ASP.NET Core Dependency Injection Deep Dive - Joonas W's blog 这篇文章我们来深入探讨ASP.NET Core.MVC Core中 ...

  5. ASP.NET Core 依赖注入最佳实践——提示与技巧

    在这篇文章,我将分享一些在ASP.NET Core程序中使用依赖注入的个人经验和建议.这些原则背后的动机如下: 高效地设计服务和它们的依赖. 预防多线程问题. 预防内存泄漏. 预防潜在的BUG. 这篇 ...

  6. ASP.NET Core 依赖注入基本用法

    ASP.NET Core 依赖注入 ASP.NET Core从框架层对依赖注入提供支持.也就是说,如果你不了解依赖注入,将很难适应 ASP.NET Core的开发模式.本文将介绍依赖注入的基本概念,并 ...

  7. ASP.NET Core 依赖注入(构造函数注入,属性注入等)

    原文:ASP.NET Core 依赖注入(构造函数注入,属性注入等) 如果你不熟悉ASP.NET Core依赖注入,先阅读文章: 在ASP.NET Core中使用依赖注入   构造函数注入 构造函数注 ...

  8. .NET Core依赖注入集成Dynamic Proxy

    在<Castle DynamicProxy基本用法>中介绍了如何将DP与Autofac集成使用,而 .NET Core有自己的依赖注入容器,在不依赖第三方容器的基础上,如何实现动态代理就成 ...

  9. net core 依赖注入问题

    net core 依赖注入问题 最近.net core可以跨平台了,这是一个伟大的事情,为了可以赶上两年以后的跨平台部署大潮,我也加入到了学习之列.今天研究的是依赖注入,但是我发现一个问题,困扰我很久 ...

随机推荐

  1. (摘自ItPub)物理standby中switchover时switchover pending的解决办法

    http://www.itpub.net/thread-1782245-1-1.html DataGuard一主一物理备,sid为primary和standby,现在要把primary切换成备库,st ...

  2. Baidu Map Web API 案例

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  3. Entity Framework with MySQL 学习笔记一(验证标签)

    直接上代码 [Table("single_table")] public class SingleTable { [Key] public Int32 id { get; set; ...

  4. BZOJ 2300 防线修建

    http://www.lydsy.com/JudgeOnline/problem.php?id=2300 题意:给点,有以下操作:删去一个点,询问这些点构成凸包的周长. 思路:用splay维护上凸壳, ...

  5. windows 查看文件被哪个进程占用

    经常当我们删除文件时,有时会提示[操作无法完成,因为文件已在另一个程序中打开,请关闭该文件并重试],到底是哪些程序呢? 有时候一个一个找真不是办法,已经被这个问题折磨很久了,今天下决心要把它解决,找到 ...

  6. HDOJ 1397 Goldbach's Conjecture(快速筛选素数法)

    Problem Description Goldbach's Conjecture: For any even number n greater than or equal to 4, there e ...

  7. 扒一扒ReentrantLock以及AQS实现原理

    提到JAVA加锁,我们通常会想到synchronized关键字或者是Java Concurrent Util(后面简称JCU)包下面的Lock,今天就来扒一扒Lock是如何实现的,比如我们可以先提出一 ...

  8. This manual page is part of Xcode Tools version 5.0

    https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.ht ...

  9. ajax弹出窗口

    提取自ZCMS的弹出框: 代替window.open.window.alert.window.confirm:提供良好的用户体验: 水晶质感,设计细腻,外观漂亮: 兼容ie6/7/8.firefox2 ...

  10. TCP/IP具体解释--三次握手和四次握手 Dos攻击

    TCP连接的状态图 TCP建立连接的三次握手过程,以及关闭连接的四次握手过程 贴一个telnet建立连接,断开连接的使用wireshark捕获的packet截图. 1.建立连接协议(三次握手) (1) ...