ASP.NET Core MVC Intermediate

Dependency injection and service lifetimes

Dependency injection (DI) is how ASP.NET Core gives your classes the services they need, instead of each class creating its own. This lesson explains the idea, how to register services, and the three lifetimes: transient, scoped and singleton.

Service lifetimes
  1. TransientAddTransient: a new instance every time one is requested. For light, stateless services
  2. ScopedAddScoped: one instance per HTTP request, shared within it. DbContext and most app services
  3. SingletonAddSingleton: one instance for the whole app until it stops. Must be thread-safe

A service must not depend on a service with a shorter lifetime, for example a singleton holding a scoped DbContext.

The idea in plain words

Without DI, a controller that sends email would write new SmtpEmailSender() itself, and every class would be tied to concrete classes, hard to test and hard to change. With DI you describe your services once in Program.cs, usually as an interface and an implementation. Any class that needs IEmailSender simply asks for it in its constructor, and the built-in container creates and passes it in.

The container also manages lifetimes: it decides when to create a new instance and when to dispose it.

Example: register and use

C#
public interface IEmailSender
{
    Task SendAsync(string to, string subject, string body);
}

public class SmtpEmailSender : IEmailSender
{
    public Task SendAsync(string to, string subject, string body)
    {
        // send through an SMTP server...
        return Task.CompletedTask;
    }
}

// Program.cs
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddTransient<PriceCalculator>();

// Any controller or service
public class OrdersController : Controller
{
    private readonly IEmailSender _email;
    public OrdersController(IEmailSender email) => _email = email;
}

Choosing a lifetime

  • Does it hold per-request data or use a DbContext? Scoped.
  • Is it stateless and cheap? Transient (or scoped).
  • Is it expensive to create and safe to share between threads, like a cache or configuration? Singleton.

Common mistakes

  • Injecting a scoped service into a singleton (a captive dependency). In Development, ASP.NET Core validates scopes and throws an error for this.
  • Using new for services inside controllers, which bypasses DI.
  • Registering mutable, non-thread-safe classes as singletons.
  • Resolving services manually from IServiceProvider everywhere (the service locator pattern) instead of constructor injection.

Interview question

What is the difference between transient, scoped and singleton services?

A transient service is created each time it is requested from the container. A scoped service is created once per scope, which in ASP.NET Core is one HTTP request, so all classes in the request share it. A singleton is created once for the lifetime of the application and shared by all requests, so it must be thread-safe. Lifetimes also decide when the container disposes the instance.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.