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.
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.
Top comments (0)