(Dependency Injection,DI)依赖注入,又称依赖关系注入,是一种软件设计模式,也是依赖倒置原则的一种体现。
依赖倒置原则的含义如下
- 上层模块不依赖下层模块。二者都依赖抽象
- 抽象不依赖细节
- 细节依赖抽象
依赖注入原则有别于传统的通过关键字new直接依赖下层模块的形式,以第三方容器注入的形式进行依赖项的管理。依赖注入是实现控制反转的一种手段,而用来实现依赖注入的技术框架又被成为IOC框架
控制反转(Inversion of Control,IOC),由于对象之间存在紧密的相互依赖关系,每个对象都需要管理依赖关系的引用,应用程序代码变得高度耦合且难以拆分。而依赖注入则改变了对象原本的依赖形式。可以实现对依赖关系的控制反转
.net core 提供原生的IOC框架(命名空间Microsoft.Extension.DependencyInjection),该框架具有轻量和易用性的特点
依赖注入提倡使用面向接口编程
  - using Microsoft.Extensions.DependencyInjection;
- using System;
- namespace ConsoleApp1
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Hello DI IOC!");
- var provider = new ServiceCollection()
- .AddSingleton<MessagePrinter>()
- .AddSingleton<IWriter, ConsoleWriter>()
- .BuildServiceProvider(validateScopes: false);
- var consoleWriter = provider.GetRequiredService<MessagePrinter>();
- consoleWriter.WriteLine();
- }
- }
- public interface IWriter
- {
- void WriteLine(string msg);
- }
- public class ConsoleWriter : IWriter
- {
- public void WriteLine(string msg)
- {
- Console.Out.WriteLine(msg);
- }
- }
- public class MessagePrinter
- {
- private IWriter _writer;
- public MessagePrinter(IWriter writer)
- {
- _writer = writer;
- }
- public void WriteLine()
- {
- _writer.WriteLine("Hello World");
- }
- }
- }
复制代码 View CodeIServiceProvider是依赖注入的核心抽象接口


对于GetRequiredService扩展方法来说,如果服务不可用,就会抛出异常;GetService扩展方法的返回类型是空的,所以是有返回空的可能性的,需要做非空检查
生命周期
- 单例(Singleton),只会创建一次对象,后续调用复用对象
- 作用域(Scoped),作用域下只生成一个实例,有人将使用的Scoped称为“请求单例”,表示在每个http请求期间创建一次
- 瞬时(Transient) ,每次调用都是创建新的对象

IServiceProvider对象提供了CreateSocpe扩展方法 使用CreateSocpe扩展方法会创建一个相应的服务范围,这个服务范围代表子容器,这个子容器获取相应的IServiceProvider对象
IServiceProvider有两种定义:一种是根容器(Root Scope)中的IServiceProvider对象,是位于应用程序顶端的容器,一般被称为ApplicationServices;另一种是通过IServiceScopeFactory服务创建的带有服务范围的IServiceProvider对象,而对于IServiceScope对象来说,拥有的是一个“范围”性的IServiceProvider对象,只可以拥有一个根容器



ASP.NET Core的作用域,在asp.net core中,每个请求都会创建一个全新的Scope(作用域)服务,在这个请求过程中创建的服务实例都会保存在当前的IServiceProvider对象上
ServiceDescriptor对象用于注册指定的服务时,对服务注册项进行描述,
作用域验证,例如,应用程序有一个Context对象,开发人员通常会将其注册为Socped生命周期
控制台实例创建ServiceCollection对象,调用AddSocped扩展方法注册。调用ISerivceprocider对象之后调用GetRequiredService扩展方法来获取实例
应该从IServiceScope对象中解析,而不是从IServiceProvider对象中解析,在asp.net core请求中框架会自动创建ServiceProviderServiceExtensions.CreateScope作用域容器,不是asp.net core 可以自行创建一个作用域


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |