DEV Community

Cover image for Dependency Injection Lifetime in .NET
Theodore Karropoulos
Theodore Karropoulos

Posted on

Dependency Injection Lifetime in .NET

.NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.

All these dependencies are registered inside the Startup.cs within ConfigureServices method of our application and must have a specific lifetime.

Service Lifetimes

Services can be registered with one of the following available lifetimes:

  • Transient
  • Scoped
  • Singleton

Transient Scope

When a service is been registered as transient it means a new instance of the service is created, every time you request it.
To register a service as transient use the AddTransient extension method. For example.

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyTransientService, MyTransientService>();
}
Enter fullscreen mode Exit fullscreen mode

Scoped Scope

When a service is registered as scoped, a new instance of the service is been created for each scope/request. Within the scope the existing instance of the service is used.
To register a service as scoped use the AddScoped extension method as shown in the following code snippet.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IMyScopedService, MyScopedService>();
}
Enter fullscreen mode Exit fullscreen mode

Singleton Scope

When a service is registered as singleton it means that only one instance of that service is been created during the application lifetime.
To register a service as singleton use the AddSingleton extension method as shown in the following code snippet.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IMySingletonService, MySingletonService>();
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)