概述

ASP.NET Core 支持依赖关系注入 (DI) 软件设计模式,这是一种在类及其依赖关系之间实现控制反转 (IoC) 的技术。

默认服务容器是 Microsoft.Extensions.DependencyInjection 。

内置的服务容器一般能满足简单的框架和部分消费者应用的需求。 建议使用内置容器,除非你需要的特定功能不受内置容器支持,例如:

属性注入

基于名称的注入

子容器

自定义生存期管理

对迟缓初始化的 Func<T> 支持

基于约定的注册

而大部分情况下,实际项目中往往是比较复杂的,所以可以使用其他第三方IOC容器,如Autofac;

Autofac

Autofac 是.Net世界中最常用的依赖注入框架之一. 相比.Net Core标准的依赖注入库, 它提供了更多高级特性, 比如动态代理和属性注入.

优点:

它是C#语言联系很紧密,也就是说C#里的很多编程方式都可以为Autofac使用,例如可以用Lambda表达式注册组件

较低的学习曲线,学习它非常的简单,只要你理解了IoC和DI的概念以及在何时需要使用它们

XML配置支持

自动装配

具体使用

1、项目中引用

 <PackageReference Include="Autofac" Version="4.9.1" /><PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.3.1" />

2、准备好类、接口

using System.Collections.Generic;namespace AspNetCoreExample.Services
{public interface IValuesService{IEnumerable<string> FindAll();string Find(int id);}
}
using System.Collections.Generic;
using Microsoft.Extensions.Logging;namespace AspNetCoreExample.Services
{public class ValuesService : IValuesService{private readonly ILogger<ValuesService> _logger;public ValuesService(ILogger<ValuesService> logger){_logger = logger;}public IEnumerable<string> FindAll(){_logger.LogDebug("{method} called", nameof(FindAll));return new[] { "value1", "value2" };}public string Find(int id){_logger.LogDebug("{method} called with {id}", nameof(Find), id);return $"value{id}";}}
}

3、替换掉内置的Ioc

using System;
using System.Linq;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;namespace AspNetCoreExample
{public class Program{public static void Main(string[] args){// The ConfigureServices call here allows for// ConfigureContainer to be supported in Startup with// a strongly-typed ContainerBuilder. If you don't// have the call to AddAutofac here, you won't get// ConfigureContainer support. This also automatically// calls Populate to put services you register during// ConfigureServices into Autofac.var host = WebHost.CreateDefaultBuilder(args).ConfigureServices(services => services.AddAutofac()).UseStartup<Startup>().Build();host.Run();}}
}
using System;
using System.Linq;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;namespace AspNetCoreExample
{// ASP.NET Core docs for Autofac are here:// https://autofac.readthedocs.io/en/latest/integration/aspnetcore.htmlpublic class Startup{public Startup(IHostingEnvironment env){var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables();this.Configuration = builder.Build();}public IConfigurationRoot Configuration { get; private set; }public void Configure(IApplicationBuilder app){app.UseMvc();}public void ConfigureContainer(ContainerBuilder builder){// Add any Autofac modules or registrations.// This is called AFTER ConfigureServices so things you// register here OVERRIDE things registered in ConfigureServices.//// You must have the call to AddAutofac in the Program.Main// method or this won't be called.builder.RegisterModule(new AutofacModule());}public void ConfigureServices(IServiceCollection services){// Use extensions from libraries to register services in the// collection. These will be automatically added to the// Autofac container.//// Note if you have this method return an IServiceProvider// then ConfigureContainer will not be called.services.AddMvc();}}
}

4、注入我们准备好的测试类、接口

using Autofac;
using AspNetCoreExample.Services;
using Microsoft.Extensions.Logging;namespace AspNetCoreExample
{public class AutofacModule : Module{protected override void Load(ContainerBuilder builder){// The generic ILogger<TCategoryName> service was added to the ServiceCollection by ASP.NET Core.// It was then registered with Autofac using the Populate method. All of this starts// with the services.AddAutofac() that happens in Program and registers Autofac// as the service provider.builder.Register(c => new ValuesService(c.Resolve<ILogger<ValuesService>>())).As<IValuesService>().InstancePerLifetimeScope();}}
}

5、小试牛刀,用起来

using System.Collections.Generic;
using AspNetCoreExample.Services;
using Microsoft.AspNetCore.Mvc;namespace AspNetCoreExample.Controllers
{/// <summary>/// Simple REST API controller that shows Autofac injecting dependencies./// </summary>/// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" />[Route("api/[controller]")]public class ValuesController : Controller{private readonly IValuesService _valuesService;public ValuesController(IValuesService valuesService){this._valuesService = valuesService;}// GET api/values[HttpGet]public IEnumerable<string> Get(){return this._valuesService.FindAll();}// GET api/values/5[HttpGet("{id}")]public string Get(int id){return this._valuesService.Find(id);}}
}

ASP.NET Core 依赖注入-集成 Autofac相关推荐

  1. ASP.NET Core依赖注入深入讨论

    这篇文章我们来深入探讨ASP.NET Core.MVC Core中的依赖注入,我们将示范几乎所有可能的操作把依赖项注入到组件中. 依赖注入是ASP.NET Core的核心,它能让您应用程序中的组件增强 ...

  2. ASP.NET Core依赖注入最佳实践,提示技巧

    分享翻译一篇Abp框架作者(Halil İbrahim Kalkan)关于ASP.NET Core依赖注入的博文. 在本文中,我将分享我在ASP.NET Core应用程序中使用依赖注入的经验和建议. ...

  3. ASP.NET Core依赖注入容器中的动态服务注册

    介绍 在ASP.NET Core中,每当我们将服务作为依赖项注入时,都必须将此服务注册到ASP.NET Core依赖项注入容器.但是,一个接一个地注册服务不仅繁琐且耗时,而且容易出错.因此,在这里,我 ...

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

    1. 前言 关于IoC模式(控制反转)和DI技术(依赖注入),我们已经见过很多的探讨,这里就不再赘述了.比如说必看的Martin Fowler<IoC 容器和 Dependency Inject ...

  5. ASP.NET Core依赖注入解读amp;使用Autofac替代实现

    1. 前言 关于IoC模式(控制反转)和DI技术(依赖注入),我们已经见过很多的探讨,这里就不再赘述了.比如说必看的Martin Fowler<IoC 容器和 Dependency Inject ...

  6. 任务21 :了解ASP.NET Core 依赖注入,看这篇就够了

    DI在.NET Core里面被提到了一个非常重要的位置, 这篇文章主要再给大家普及一下关于依赖注入的概念,身边有工作六七年的同事还个东西搞不清楚.另外再介绍一下.NET  Core的DI实现以及对实例 ...

  7. ASP.NET Core依赖注入初识与思考

    一.前言 在上一篇中,我们讲述了什么是控制反转(IoC)以及通过哪些方式实现的.这其中,我们明白了,「控制反转(IoC)」 是一种软件设计的模式,指导我们设计出更优良,更具有松耦合的程序,而具体的实现 ...

  8. 【ASP.NET Core】ASP.NET Core 依赖注入

    一.什么是依赖注入(Denpendency Injection) 这也是个老身常谈的问题,到底依赖注入是什么? 为什么要用它? 初学者特别容易对控制反转IOC(Iversion of Control) ...

  9. 一文读懂Asp.net core 依赖注入(Dependency injection)

    一.什么是依赖注入 首先在Asp.net core中是支持依赖注入软件设计模式,或者说依赖注入是asp.net core的核心: 依赖注入(DI)和控制反转(IOC)基本是一个意思,因为说起来谁都离不 ...

最新文章

  1. Window编程主函数详解
  2. 亲爱的,别把上帝缩小了 ---- 读书笔记2
  3. ACL 2021 | 北京大学KCL实验室:如何利用双语词典增强机器翻译?
  4. uva 12222——Mountain Road
  5. 飞腾 linux 内核,FT2004-Xenomai
  6. 如何在js中使用ajax请求数据,在 JS 中怎么使用 Ajax 来进行请求
  7. Android 系统(268)---native保活5.0以下方案推演过程以及代码详述
  8. 区块链100讲:Vitalik Buterin-以太坊Casper惩罚条件的最小化
  9. java随机数_Java随机
  10. 入门 Angular 2 杂记
  11. 呼吁各行业实现无纸化办公
  12. 关于结构体嵌套的字节大小的问题
  13. c51单片机流水灯程序汇编语言,单片机流水灯汇编程序,8路流水灯汇编语言程序的写法...
  14. 日本向日葵8号卫星数据下载
  15. 记一次闲置电视盒子乐视C1S折腾entware
  16. 雷电9模拟器安装magisk和lsposed
  17. 【算法:leetcode】双指针:142. 环形链表 II 633. 平方数之和
  18. Android 创建随机数生成器
  19. html都有哪些事件,HTML有哪些事件属性?
  20. 网上教务评教管理系统(教学评价系统)

热门文章

  1. Web应用性能分析工具—HAR文件
  2. Java泛型主题讨论
  3. GitGitHub语法大全
  4. 详解go语言的array和slice 【二】
  5. 设计模式(10)-----模板方法模式
  6. Fragment使用--文章集锦
  7. 编程算法 - 切割排序 代码(C)
  8. mongo-rename操作
  9. SQL Server索引进阶第十篇:索引的内部结构
  10. hdu 1863(最小生成树kruskal)