当前位置:网站首页>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
边栏推荐
- MYSQL05_ Ordr by sorting, limit grouping, group by grouping
- Development notes of raspberry pie (12): start Advantech industrial control raspberry pie uno-220 Kit (I): introduction and operation of the system
- Source generator actual combat
- TP5 email (2020-05-27)
- Openfeign service call
- FileNotFoundError: [Errno 2] No such file or directory
- Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)
- 7-11 重排链表 (25 分)
- 由于3²+4²=5²,所以称‘3,4,5‘为勾股数,求n(包括n)以内所有勾股数数组。
- Simple example of using redis in PHP
猜你喜欢

Tencent video VIP member, weekly card special price of 9 yuan! Tencent official direct charging, members take effect immediately!

2022A特种设备相关管理(电梯)上岗证题库及模拟考试

全网讲的最细,软件测试度量,怎样优化软件测试成本提高效率---火爆

Recursion - outputs continuously increasing numbers

Openfeign details show

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).

Fight leetcode again (290. Word law)

Passing object type parameters through openfeign

C language to achieve address book - (static version)

be based on. NETCORE development blog project starblog - (1) why do you need to write your own blog?
随机推荐
C read / write binary file
建立与遍历二叉树
Small companies don't make formal offers
由于3²+4²=5²,所以称‘3,4,5‘为勾股数,求n(包括n)以内所有勾股数数组。
SQL statement - DDL
中后二叉建树
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
Find the number of leaf nodes of binary tree
The whole network is the most complete. How to do interface automation test? Proficient in interface automation test details
Laravel new route file
Laravel's own paging query
类似Jira的十大项目管理软件
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (9)
The most detailed in the whole network, software testing measurement, how to optimize software testing cost and improve efficiency --- hot
对.NET未来的一点感悟
一套关于 内存对齐 的C#面试题,做错的人很多!
LNMP MySQL allows remote access
Fight leetcode again (290. Word law)
Xamarin效果第二十一篇之GIS中可扩展浮动操作按钮
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).