当前位置:网站首页>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
- Simple example of using redis in PHP
- 一套关于 内存对齐 的C#面试题,做错的人很多!
- LNMP MySQL allows remote access
- C syntax pattern matching [switch expression]
- The backtracking of stack is used to solve the problem of "the longest absolute path of file"
- 【新版发布】ComponentOne 新增 .NET 6 和 Blazor 平台控件支持
- 最通俗易懂的依赖注入与控制反转
- The most detailed in the whole network, software testing measurement, how to optimize software testing cost and improve efficiency --- hot
- 微软是如何解决 PC 端程序多开问题的
猜你喜欢
Opencv combines multiple pictures into video
Drawing polygons with < polygon / > circular array in SVG tag
TP5 inherits base and uses the variables in base
ASP.NET 6 中间件系列 - 条件中间件
Blazor University (11)组件 — 替换子组件的属性
利用栈的回溯来解决“文件的最长绝对路径”问题
Yes Redis using distributed cache in NE6 webapi
REINFORCE
Er and eer models
Realize QQ login with PHP
随机推荐
C syntax pattern matching [switch expression]
Depth deterministic strategy gradient (ddpg)
Load view Caton
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (10)
Detailed explanation of distributed things
Summary of interface automation interview questions for software testing
建立与遍历二叉树
[ncnn] - the meaning of - 23300 in param
C read / write binary file
Golden nine silver ten interview season, you are welcome to take away the interview questions (with detailed answer analysis)
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (8)
MYSQL03_ SQL overview, rules and specifications, basic select statements, display table structure
Array and collection types passed by openfeign parameters
Service avalanche effect
Vs code setting line feed
.NET7之MiniAPI(特别篇):.NET7 Preview3
A set of C interview questions about memory alignment. Many people make mistakes!
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (7)
Simple example of using redis in PHP
中后二叉建树