Lifetime options in ASP.NET Core

Posted by

.NET Core’s Dependency Injection (DI) framework provides three-lifetime options for resolving dependencies: Transient, Scoped, and Singleton.

  • Transient: A new instance of the service is created each time it is requested.
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyDependency, MyDependency>();
}
  • Scoped: A single instance of the service is created per client request (e.g., per HTTP request).
public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IMyDependency, MyDependency>();
}
  • Singleton: A single instance of the service is created the first time it is requested and re-used for all subsequent requests.
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IMyDependency, MyDependency>();
}

You choose the lifetime that best fits your service’s needs, depending on whether you want a new instance every time or to re-use an existing instance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.