当前位置:网站首页>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
边栏推荐
猜你喜欢

Recommend reading | share the trader's book list and ask famous experts for trading advice. The trading is wonderful

Openfeign details show

类似Jira的十大项目管理软件

MAUI初体验:爽

MYSQL05_ Ordr by sorting, limit grouping, group by grouping

Ningde's position in the times is not guaranteed?

Openfeign timeout setting

准备一个月去参加ACM,是一种什么体验?

Recursion - outputs continuously increasing numbers

Passing object type parameters through openfeign
随机推荐
OLED multi-level menu record
Realize QQ login with PHP
C syntax pattern matching [switch expression]
How to count the number of all files in a directory under win10 system
Laravel8- use JWT
Introduction and use of openfeign component
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
Blazor University (12)组件 — 组件生命周期
Find the number of leaf nodes of binary tree
一套关于 内存对齐 的C#面试题,做错的人很多!
Passing object type parameters through openfeign
c#可变参数params的介绍
How does Microsoft solve the problem of multiple PC programs
MYSQL_ From mastery to abandonment
建立与遍历二叉树
How does Microsoft solve the problem of multiple programs on PC side -- internal implementation
基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客?
Use split to solve the "most common words" problem
Summary of software test interview questions
2022A特种设备相关管理(电梯)上岗证题库及模拟考试