当前位置:网站首页>The most easy to understand service container and scope of dependency injection
The most easy to understand service container and scope of dependency injection
2022-04-23 03:08:00 【Dotnet cross platform】
Recommended attention 「 Code Xia Jianghu 」 Add Star standard , Never forget the Jianghu Affairs
This article is ASP.NET 6 The second in the dependency injection series 3 piece , Click the blue word above to Read the entire series .
In the last article , We discuss the basic usage and lifecycle of dependency injection .
Next , In this article , Let's continue to understand the concepts related to service containers .

Service container
Let's review what a service container is .
In the last article , We mentioned , The service container in the dependency injection system will save , A service instance with a valid life cycle created by the dependency injection system .
「 stay ASP.NET Dependency injection system , Service containers can be divided into root containers and child containers .」
The first container created in the dependency injection system is the root container , And only one root container will exist , Sub containers can have many .
The difference is :
「 The instances saved in the root container are visible to all child containers .」
「 The instances saved in the sub container are not visible to each other .」
「 Service instances with different lifecycle patterns , Will be stored in different containers .」
The service instance of singleton mode is saved in the root container .
The service instance of the scope pattern is saved in the scope container , A scoped container is a child container .
Because the sub containers are not visible to each other , So the instances saved in the scope schema , Will only survive in this scope .
Service instances in transient mode will not be saved in any container .
Sub container example
Let's look at this example , Demonstrates the differences between three different lifecycle patterns :
public interface IAccount{ }
public interface IMessage{ }
public interface ITool{ }
public class Base
{
public Base()
{
Console.WriteLine($"Created:{GetType().Name}");
}
}
public class Account: Base, IAccount {}
public class Message:Base, IMessage {}
public class Tool:Base, ITool {}
public static void Main()
{
// Create a service collection
var serviceCollection = new ServiceCollection()
.AddTransient<IAccount, Account>()
.AddScoped<IMessage, Message>()
.AddSingleton<ITool, Tool>();
// establish ServiceProvider Object represents the service root container
var root = serviceCollection.BuildServiceProvider();
// Create sub containers 1
var child1 = root.CreateScope().ServiceProvider;
// Create sub containers 2
var child2 = root.CreateScope().ServiceProvider;
// Get sub container 1 Service instance of
GetService<IAccount>(child1);
GetService<IMessage>(child1);
GetService<ITool>(child1);
Console.WriteLine();
// Get sub container 2 Service instance of
GetService<IAccount>(child2);
GetService<IMessage>(child2);
GetService<ITool>(child2);
}
// To validate the lifecycle , Get twice in a row
public static void GetService<T>(IServiceProvider provider)
{
provider.GetService<T>();
provider.GetService<T>();
}
The code to create the container is the same as the example in the previous article , Here we focus on two CreateScope Use of methods :
var root = serviceCollection.BuildServiceProvider();
var child1 = root.CreateScope().ServiceProvider;
var child2 = root.CreateScope().ServiceProvider;
By using the root container CreateScope Method , You can create ServiceScope object , It represents the scope of the service .
In each scope , There is one. ServiceProvider object , It represents the service container .
We can use the service root container , To create its sub container .
Last , We use two sub containers to get the corresponding service instances :
// Get sub container 1 Service instance of
GetService<IAccount>(child1);
GetService<IMessage>(child1);
GetService<ITool>(child1);
Console.WriteLine();
// Get sub container 2 Service instance of
GetService<IAccount>(child2);
GetService<IMessage>(child2);
GetService<ITool>(child2);
Base Constructor in class , The specific instance created will be printed in the console , Therefore, the running result of this example is as follows :

Through the results, we can find :
Account The service life cycle is instantaneous , So when you get the instance of the service twice , Will create a new Account object .
Message The lifecycle of a service is the scope , If you get its service instance in the same sub container , Then only one will be created Message object , And there are two sub containers , So we created two Message object .
Tool The life cycle of a service is a singleton , Service instances in singleton mode , Save only on the root container , And visible to all sub containers . Because the two sub containers have the same root container , So only when you get it for the first time Tool Object will be created .
Service scope
Each newly created service scope ServiceScope Objects have a ServiceProvider object , It represents the service container .
「 The root container can create sub containers , Sub containers can also be created .」
But all sub containers are level , That is, whoever created it , They are all sub containers of the root container , There is no such thing as “ Grandson container ”.
Although the root container and the child container are parent-child , But in fact 「 The child container does not know who its parent container is , They only know who the root container is 」.
In the eyes of the sub container , Only you have no father .
about ASP.NET applications , Service scopes have very clear boundaries , That is, every one of them HTTP Request context for .
in other words , The scope of each request is bound with the scope of the service .
We now know , Containers can be divided into root containers and sub containers .
In fact, root containers and child containers also have different identities , Let's take a look at this picture :

「 At the top is the root container , Also called application container .」
「 Branches are sub containers , They are all sub containers created and released upon request , Also called request container .」
stay ASP.NET During application initialization , A large number of built-in service instances will be used , These service instances are provided by the application container .
When processing a specific request ,ASP.NET The framework will respond to the current request , Create a service scope object .
The request container in this service scope object , It is used to provide the service instance needed in the current request processing .
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/202204230301333508.html
边栏推荐
- [format] simple output (2)
- 使用split来解决“最常见的单词”问题
- The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
- Xamarin效果第二十二篇之录音效果
- 宁德时代地位不保?
- Tips in MATLAB
- Use of MySQL command line client and common commands
- Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
- C# 读写二进制文件
- Openfeign timeout setting
猜你喜欢

MYSQL04_ Exercises corresponding to arithmetic, logic, bit, operator and operator

Small companies don't make formal offers

MySQL port is occupied when building xampp

Tencent video VIP member, weekly card special price of 9 yuan! Tencent official direct charging, members take effect immediately!
![[software testing] understand the basic knowledge of software testing](/img/ff/8fcd4b88de28505989aaf517d16113.png)
[software testing] understand the basic knowledge of software testing

TP5 email (2020-05-27)

MAUI初体验:爽

Recursion - outputs continuously increasing numbers

Source generator actual combat

ASP.NET 6 中间件系列 - 条件中间件
随机推荐
先中二叉建树
Laravel's own paging query
Some problems encountered in setting Django pure interface, channel and MySQL on the pagoda panel
ASP.NET 6 中间件系列 - 执行顺序
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
荐读 | 分享交易员的书单,向名家请教交易之道,交易精彩无比
If the deep replication of objects is realized through C #?
Middle and rear binary tree
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).
Xamarin效果第二十二篇之录音效果
C syntax sugar empty merge operator [?] And null merge assignment operator [? =]
Openfeign details show
Er and eer models
腾讯视频VIP会员,周卡特价9元!腾讯官方直充,会员立即生效!
树莓派开发笔记(十二):入手研华ADVANTECH工控树莓派UNO-220套件(一):介绍和运行系统
使用split来解决“最常见的单词”问题
C read / write binary file
建立与遍历二叉树
C language to achieve address book - (static version)
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (9)