In .NET's dependency injection there are three major lifetimes: Singleton, Scoped, and Transient.
They are initiated with AddSingleton
, AddScoped
, and AddTransient
respectively.
// Singleton
builder.Services.AddSingleton<ICookies, Cookies>();
// Scoped
builder.Services.AddScoped<ICache, Cache>();
// Transient
builder.Services.AddTransient<ILookup, Lookup>();
Singleton creates a single instance once and reuses the same object in all calls. Use Singletons where you need to maintain application wide state, for example, application configuration, logging service, caching of data, etc.
Scoped lifetime services are created once per request. For example, in MVC it creates one instance for each HTTP request, but it uses the same instance in the other calls within the same web request.
Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless services. Since they are created every time, they will use more memory & resources and can have negative impact on performance.