当前位置:网站首页>ASP. Net core dependency injection service life cycle
ASP. Net core dependency injection service life cycle
2022-04-23 17:05:00 【begeneral】
Dependency injection services include 3 A life cycle :Transient;Scoped;Singleton
Transient: Ready to use, ready to build , Discard after use . That is to create an instance of this service every time you get an instance of this service .
Scoped: This type of service instance is saved in the current dependency injection container (IServiceProvider) On , This will be explained in detail later .
Singleton: Single case . That is, only one service instance is saved
Let's do an example demonstration , Let us have a deeper understanding of this 3 Medium life cycle
My test environment :win10+vs2019+.net core 3.1
Create a new one .NET CORE The console application , add to NuGet package :Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.DependencyInjection.Abstractions
Create a new one Base class , Inherited from IDisposable Interface . In this way, we can know when the instance inherited from the base class is released
Base The code for the class is as follows :
public class Base:IDisposable
{
public Base() => Console.WriteLine($"An Instance of {GetType().Name} is created");
public void Dispose() => Console.WriteLine($"The Instance of {GetType().Name} is disposed");
}
Then define 3 Interface , Represents the service type :
public interface IBaz
{
}
public interface IBar
{
}
public interface IFoo
{
}
Definition 3 Each implementation implements this 3 Interface classes , These classes inherit from Base and IDispose
public class Baz:Base,IBaz
{
}
public class Bar:Base,IBar
{
}
public class Foo:Base,IFoo
{
}
The next in Main Function to create a dependency injection container . This container is in using Created in statement , So when using At the end of the statement execution, it will call Dispose To release this container
static void Main(string[] args)
{
using (var root = new ServiceCollection().AddTransient<IFoo, Foo>()
.AddScoped<IBar, Bar>()
.AddSingleton<IBaz, Baz>().BuildServiceProvider())
{
using (var scope = root.CreateScope())
{
var provider = scope.ServiceProvider;
provider.GetService<IFoo>();
provider.GetService<IBar>();
provider.GetService<IBaz>();
Console.WriteLine("child container is disposed");
}
Console.WriteLine("root container is disposed");
}
Console.ReadKey();
}
Let's create a root container , Then create a sub container with this root container .3 The life cycles of service instances are Transient、Scoped、Singleton. The results are as follows :

Service instances are created when obtaining service instances , However, the release of instances is not together .Bar and Foo The life cycle of Scoped and Transient,
So when the sub container is released , this 2 An instance is released .Baz The life cycle of is a single case , It is stored in the root container (root) Inside , So when the sub container is released
When , It didn't release , The root container is not released until it is released .
about ASP.NET CORE applications , It has a global root container bound to the current application IServiceProvider object . For each request processed ,ASP.NET CORE
The framework will use this root container to create a service scope based on the current request ( That is to say Scoped Life cycle ), And use the IServiceProvider Object to provide the... Required for request processing
Service instance . After the request is processed ,Scoped The instance of the life cycle is terminated , The corresponding sub container is also released .
So in the same request ,Scoped Instances of the lifecycle are created only once . You can also try , Use... In the same request GetService Get... Many times Scoped Examples of life cycles ,
Then get... In multiple requests Scoped Examples of life cycles , In this way, everyone's understanding will be more profound .
版权声明
本文为[begeneral]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230554081977.html
边栏推荐
- Lock lock
- 【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
- 1-4 configuration executable script of nodejs installation
- . net cross platform principle (Part I)
- Encapsulating the logging module
- 扫码登录的原理你真的了解吗?
- org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
- Shortcut keys (multiline)
- Aiot industrial technology panoramic structure - Digital Architecture Design (8)
- Rtklib 2.4.3 source code Notes
猜你喜欢

Idea of batch manufacturing test data, with source code

Detailed explanation of Milvus 2.0 quality assurance system

Net standard

Detailed explanation of information abstract, digital signature, digital certificate, symmetric encryption and asymmetric encryption

C# Task. Delay and thread The difference between sleep

VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN

Grpc gateway based on Ocelot

信息摘要、数字签名、数字证书、对称加密与非对称加密详解

Nifi fast installation and file synchronization

TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
随机推荐
[markdown notes]
Grpc gateway based on Ocelot
Wiper component encapsulation
拷贝构造函数 浅拷贝与深拷贝
How much do you know about the process of the interview
Get the column name list of the table quickly in Oracle
Bytevcharts visual chart library, I have everything you want
Generation of barcode and QR code
Smart doc + Torna generate interface document
ByteVCharts可视化图表库,你想要的我都有
◰GL-阴影贴图核心步骤
Document operation II (5000 word summary)
MySQL master-slave replication
Sub database and sub table & shardingsphere
Preliminary understanding of promse
The new MySQL table has a self increasing ID of 20 bits. The reason is
Go language, array, string, slice
Some problems encountered in recent programming 2021 / 9 / 8
网络安全之渗透靶场实战详解
Decimal format decimal / datetime conversion processing