Asp.Net Core of Bureau: Dependency Injection

List


Foreword

本文介绍Asp.Net Core中默认的依赖注入(DI)模式。

surroundings

1.Visual Studio 2017
2.Asp.Net Core 2.2 

Start

Hand: Description dependency injection

1. An example of
主机和主机中硬盘,可以说主机中硬盘是主机的依赖项,若更换硬盘,需拆主机。
若将硬盘通过USB接口外接,那么只需将新硬盘接入USB口即可。
2. Sample Code
 
 
3. Inversion of Control (IoC)
 
 
 
 
控制反转:将依赖交给第三方容器管理。
控制反转与依赖注入的关系:控制反转是一种思想,依赖注入是控制反转的一种实现。
4. Dependency injection (DI)
现在再回到Startup中看看Asp.Net Core中的依赖注入。
 
 
1.代码中这些均为依赖注入,这些由框架实现,以后源码解读时再做详述;
2.下面介绍Asp.Net Core自带的依赖注入框架对服务依赖的注册和使用。

Second hand: dependency injection - Registration Service

Asp.Net Core中向容器中注册服务有三种方法,其区别在于生命周期不同:
    - AddTransient:每次请求会获取一个新实例,即:每次GetService都会获取一个新实例 - AddScoped :每个请求会获取一个新实例,即:在一个请求内,每次GetService都会获得同一个实例 - AddSingleton:每次请求会获取同一个实例,即:在应用程序生命周期内,每次GetService都会获得同一个实例 
 
 
 
 
 
 
所说的生命周期实际对应于类实例的创建时机,GetService实际是获取类的实例。
容器根据注册方式不同,判断是否需要创建新实例返回。

Firsthand: Dependency Injection - using the service

Use 1.Startup
 
 
2.Controller constructor injection
 
 
 
 
 
 
3.View injection
在Startup中的注册方式同Controller,这里只显示在View注入方式。  
 
 
 
 

Outcome

本文介绍Asp.Net Core中默认的依赖注入(DI)模式,下局介绍读取配置文件,待续...

List



Author: home dotNET the
link: https: //www.jianshu.com/p/412f62ef55dc
Source: Jane book
Jane book copyright reserved by the authors, are reproduced in any form, please contact the author to obtain authorization and indicate the source.

Guess you like

Origin www.cnblogs.com/Jeely/p/10959852.html