ASP.NET Core supports the dependency injection (DI) software design pattern that allows us to register services and control how these services will be instantiated and injected in different components. Some services will be instantiated for a short time and will be available only in a particular component and request. Some will be instantiated just once and will be available throughout the application. Here are the service lifetimes available in ASP.NET Core.
Table of Contents
Singleton
A single instance of the service class is created, stored in memory and reused throughout the application. We can use Singleton for services that are expensive to instantiate. We can register Singleton service using the AddSingleton method as follows:
services.AddSingleton<IProductService, ProductService>();
Scoped
The service instance will be created once per request. All middlewares, MVC controllers, etc. that participate in handling of a single request will get the same instance. A good candidate for a scoped service is an Entity Framework context. We can register Scoped service using the AddScoped method as follows:
services.AddScoped<IProductService, ProductService>();
Transient
Transient lifetime services are created each time they’re requested. This lifetime works best for lightweight, stateless services. We can register Transient service using the AddTransient method as follows:
services.AddTransient<IProductService, ProductService>();
If you want to visualize the above concepts then here is an infographic for your quick reference.
Thnaks it was useful for me!
Excellent content! Thank you for putting in the time required and the crystal clear explanations/drawings!
Good source for .Net core content. Easy to understand and good explanation. Thanks for posting such a posts. Keep us posting with the different latest .Net topics.
Thank you for the clear explanation about the concept..
If you could provide some examples.. It will add some more values..
Way cool! Some extremely valid points! I appreciate you penning this post and also the rest of the website is also very good. Ula Horten Baudoin
Amazing keep creating contents like this. Really appreciate