当前位置:网站首页>The most understandable life cycle of dependency injection
The most understandable life cycle of dependency injection
2022-04-23 03:08:00 【Dotnet cross platform】
This article is ASP.NET 6 The second in the dependency injection series , Click the blue word above to Read the entire series .
In the last article , We discussed what dependency injection and control inversion are , And what it does .
In this article , Let's first demonstrate the basic usage of dependency injection , Then we'll talk about life cycle patterns .
Basic usage
.NET The dependency injection component mainly involves two packages :
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
</ItemGroup>
Abstractions The package at the end defines the interface and basic data types , The specific implementation is made by No Abstractions End of the package to provide .
For example, dependency injection components , Abstract interfaces and necessary types are defined in Microsoft.Extensions.DependencyInjection.Abstractions
The package , The specific implementation is in Microsoft.Extensions.DependencyInjection
In bag .
.NET Many class libraries and components in , When designing, we will consider this kind of “ Abstraction and Implementation ” The separation of .
stay ASP.NET Dependency injection system , We need to pass a by IServiceCollection Interface to complete the registration of services , So we call it a service collection .
You can think of a service collection as a roster of services , Service registration is actually in this roster , Register the basic information of the service type , So that when needed , The dependency injection control system can find it .
Through the service collection, you can create a service provider , It is expressed as a ServiceProvider object , As shown below :
public static class Sample01
{
public interface IAccount{ }
public interface IMessage{ }
public interface ITool{ }
public class Account: IAccount{}
public class Message: IMessage{}
public class Tool: ITool{}
public static void Run()
{
// Create a service collection
var serviceCollection = new ServiceCollection();
// Registration service
serviceCollection.AddTransient<IAccount, Account>();
serviceCollection.AddScoped<IMessage, Message>();
serviceCollection.AddSingleton<ITool, Tool>();
// Create service provider objects
var serviceProvider = serviceCollection.BuildServiceProvider();
}
}
In this sample code , There are three interfaces , And implemented three classes .
Every interface here can be regarded as a service , Each class is the concrete implementation of the service .
We can provide objects through services , Any type of service that has been registered , As shown below :
serviceProvider.GetService<IAccount>();
serviceProvider.GetService<IMessage>();
serviceProvider.GetService<ITool>();
Service registration
.NET Dependency injection components adopt a lifecycle approach , To manage the service instances it provides .
The so-called life cycle , It refers to the service instance created by the dependency injection component , How long can we survive .
There are three modes of life cycle : instantaneous (Transient)、 Scope (Scoped)、 Single case (Singleton).
When we sign up for the service , You must specify which lifecycle pattern the service belongs to , For example, the code example just now :
serviceCollection.AddTransient<IAccount, Account>();
serviceCollection.AddScoped<IMessage, Message>();
serviceCollection.AddSingleton<ITool, Tool>();
From the name of the registration method Addxxxx
It can be seen that , The life cycle patterns of registered services are 「 instantaneous \ Scope \ Single case 」.
Because each service can have multiple implementations , So when registering a service , You can register multiple different implementation classes for the same service .
Although you can register multiple implementation classes of the service , however GetService
Method can only return an instance of one of the implementation classes , That is, the last registered implementation class .
If you want to get all the implementations of a service , We can look at this example :
public static class Sample02
{
//...
public abstract class Base { }
public class Account:Base, IAccount{}
public class Message:Base, IMessage{}
public class Tool:Base, ITool{}
public static void Run()
{
// Create a service collection
var serviceCollection = new ServiceCollection();
// Registration service
serviceCollection.AddTransient<Base, Account>();
serviceCollection.AddScoped<Base, Message>();
serviceCollection.AddSingleton<Base, Tool>();
// Create service provider objects
var serviceProvider = serviceCollection.BuildServiceProvider();
// Get the service collection
var services = serviceProvider.GetServices<Base>().ToList();
}
}
In the example, a Base abstract class , The other types are Base The concrete class .
This relationship between abstract classes and concrete classes , Similar to the relationship between interface and implementation class , So you can also register with the dependency injection system .
Use GetServices
Method can get the type collection of a service , Pay attention to this Service It's in the plural .
In the example, we return a Base Class collection , The elements of a collection are registered 3 A concrete class instance .
Life cycle patterns
Through the previous example , We can find out , There are several methods of service registration , Each method corresponds to a different life cycle .
So what is a life cycle ?
Simply speaking , The service life cycle represents the lifetime of each service instance .
Why should a service instance in a dependency injection system define a lifecycle ?
Because the dependency injection system , Manage the service instance of the whole application .
When we develop applications , Must have used a single example . Objects designed as singleton patterns , Throughout the application lifecycle , There is one and only one .
Ordinary objects that are not singleton patterns , They are built with use , Throw away as soon as you use it .
Since the dependency injection system manages the service instances of the whole application , So whether it's a noble singleton 、 There are still no ordinary objects of human rights , They are all part of the dependency injection system .
therefore , In order for the dependency injection system to distinguish which object belongs to which mode , There are different patterns of life cycles .
We said earlier , There are three modes of life cycle : instantaneous 、 Scope and singleton .
among , Instantaneity and singleton are relatively simple to understand .
「 instantaneous , There is no survival time .」
in other words , Every time a transient service instance is obtained from the dependency injection system , Will create a new object .
The service container in the dependency injection system will not save it , That is, ordinary objects without the right to exist .
「 Single case , It will always exist , Same life as application .」
in other words , The first time a service instance of a singleton is obtained from the dependency injection system , Will create a new object .
The service container in the dependency injection system will save it , Every time you use it, you get it directly from the container , That is, the noble singleton .
「 Scope , It's not so intuitive to understand , It needs to be explained in combination with the scene .」
such as , stay ASP.NET The application of , Every request from outside , Can be understood as a request scope . Different requests , Different request scopes .
In the same request scope , Get the service instance of scope mode and the service instance of singleton mode , Have the same performance .
in other words , The first time you get a service instance from the dependency injection system , Will create a new object .
The dependency injection system will open a single room for this scope in the service container , Save the object separately .
When the request ends , The request scope will be destroyed , The single room will naturally disappear , The objects saved in it will also be destroyed .
therefore , Object instances that survive in this pattern , They only work in their own domain , Different domains do not interfere with each other .
thus it can be seen , Once a service has a life cycle , Then the dependency injection system can , To save and manage their instances .
More highlights , Please pay attention to me. ▼▼
If you like my article , that
Watching and forwarding is my greatest support !
( Stamp the blue words below to read )
Recommends WeChat official account : Code Xia Jianghu
I think it's good , Point and watch before you go
版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230301333426.html
边栏推荐
- 在.NE6 WebApi中使用分布式缓存Redis
- ASP. Net 6 middleware series - execution sequence
- Basic SQL (VIII) data update operation practice
- 最通俗易懂的依赖注入与控制反转
- 腾讯视频VIP会员,周卡特价9元!腾讯官方直充,会员立即生效!
- Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
- Openfeign details show
- 全网最全,接口自动化测试怎么做的?精通接口自动化测试详解
- [authentication / authorization] customize an authentication handler
- 最通俗易懂的依赖注入之生命周期
猜你喜欢
Array and collection types passed by openfeign parameters
利用栈的回溯来解决“文件的最长绝对路径”问题
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (8)
Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
最通俗易懂的依赖注入之服务容器与作用域
全网讲的最细,软件测试度量,怎样优化软件测试成本提高效率---火爆
Drawing polygons with < polygon / > circular array in SVG tag
FileNotFoundError: [Errno 2] No such file or directory
Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
Due to 3 ²+ four ²= five ², Therefore, we call '3,4,5' as the number of Pythagorean shares, and find the array of all Pythagorean shares within n (including n).
随机推荐
Swap the left and right of each node in a binary tree
In redis cluster, the master node fails, and the IP changes after the master-slave switch. The client does not need to deal with it
利用正反遍历来解决“字符的最短距离”问题
交换二叉树中每个结点的左和右
Simple example of using redis in PHP
Source generator actual combat
ASP. Net and ASP NETCORE multi environment configuration comparison
准备一个月去参加ACM,是一种什么体验?
Impact of AOT and single file release on program performance
宁德时代地位不保?
Notes sur le développement de la tarte aux framboises (XII): commencer à étudier la suite UNO - 220 de la tarte aux framboises de contrôle industriel advantech (i): Introduction et fonctionnement du s
Source Generator实战
MYSQL05_ Ordr by sorting, limit grouping, group by grouping
Openfeign timeout setting
[format] simple output (2)
Laravel8- use JWT
利用栈的回溯来解决“文件的最长绝对路径”问题
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
C read / write binary file
Creating wechat voucher process with PHP