ASP.NET Core Service Lifetimes (Infographic)

You are currently viewing ASP.NET Core Service Lifetimes (Infographic)

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.

ASP.NET Core Service Lifetimes Infographic
READ ALSO:  7 Productivity Tips for Developers (Infographic)

This Post Has 6 Comments

  1. Curt Krueger

    Excellent content! Thank you for putting in the time required and the crystal clear explanations/drawings!

  2. Mahesh

    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.

  3. Krishna

    Thank you for the clear explanation about the concept..

    If you could provide some examples.. It will add some more values..

  4. film

    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

  5. Keyran Joshi

    Amazing keep creating contents like this. Really appreciate

Leave a Reply