Clean Architecture in ASP.NET Core :👈 👉:Middleware Explained

ASP.NET Core Dependency Injection: Advanced Concepts, Lifetimes and Best Practices

ASP.NET Core Dependency Injection: Advanced Concepts, Lifetimes and Best Practices

1. Introduction

Dependency Injection (DI) is a design pattern used to provide an object with the dependencies it needs instead of allowing the object to create those dependencies itself.

ASP.NET Core has a built-in Dependency Injection container that manages object creation, dependency resolution, and object lifetimes.

For example, consider a ProductService that needs a ProductRepository to retrieve products from a database.

Without Dependency Injection:

public class ProductService
{
    private readonly ProductRepository _repository;
    public ProductService()
    {
        _repository = new ProductRepository();
    }
    public void GetProducts()
    {
        _repository.GetAll();
    }
}

Here, ProductService creates its own dependency. It is tightly coupled to ProductRepository.

If the repository implementation changes, ProductService may also need to change.

With Dependency Injection:

public class ProductService
{
    private readonly IProductRepository _repository;
    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
    public void GetProducts()
    {
        _repository.GetAll();
    }
}

Now ProductService depends on an interface rather than a concrete implementation. ASP.NET Core provides the required implementation through its DI container.

Key idea: A class should declare what it needs. The DI container should be responsible for providing those dependencies.

2. Table of Contents

  1. Why Dependency Injection Is Required
  2. Inversion of Control vs Dependency Injection
  3. How the ASP.NET Core DI Container Works
  4. Service Registration and Resolution
  5. Three DI Lifetimes
  6. Lifetime Comparison and Examples
  7. Captive Dependencies
  8. Scopes and IServiceScopeFactory
  9. Constructor Injection
  10. Other Injection Techniques
  11. Advanced Service Registration
  12. Open Generic Registrations
  13. Keyed Services in .NET
  14. Options Pattern
  15. Factory-Based Registrations
  16. Service Disposal and Cleanup
  17. Dependency Injection in Middleware
  18. DI in Background Services
  19. Third-Party DI Containers
  20. Testing Services with Dependency Injection
  21. Performance Considerations
  22. Best Practices
  23. Common Mistakes
  24. Interview Questions and Answers
  25. Summary

3. Why Dependency Injection Is Required

Consider an application with the following dependencies:

ProductsController ProductService ProductRepository SQL Server

Without DI, classes may create their dependencies directly using the new keyword.

This creates several problems:

  • Tight coupling: A class depends on a specific implementation.
  • Difficult unit testing: Replacing real dependencies with mocks or fakes becomes harder.
  • Code duplication: Multiple classes may create the same dependencies independently.
  • Lifetime management: Developers must manually manage object creation and cleanup.
  • Reduced flexibility: Replacing an implementation may require changes in multiple classes.

With Dependency Injection

ASP.NET Core DI Container Creates and manages objects ProductsController ProductService IProductRepository ProductRepository SQL Server

The DI container creates the objects and supplies their dependencies automatically.

Benefits:

  • Loose coupling between components.
  • Improved unit testing.
  • Centralized object creation.
  • Automatic lifetime management.
  • Easy replacement of implementations.
  • Better maintainability.

4. Inversion of Control vs Dependency Injection

Inversion of Control (IoC) is a broader design principle in which control over object creation or execution flow is transferred from a class to an external mechanism or framework.

Dependency Injection is one way of implementing Inversion of Control.

Without IoC

public class OrderService
{
    private readonly EmailService _emailService;
    public OrderService()
    {
        _emailService = new EmailService();
    }
}

OrderService controls the creation of EmailService.

With IoC and DI

public class OrderService
{
    private readonly IEmailService _emailService;
    public OrderService(IEmailService emailService)
    {
        _emailService = emailService;
    }
}

The external DI container controls object creation and supplies the dependency.

Concept Meaning
IoC A principle that transfers control to an external mechanism.
DI A technique that supplies dependencies from outside a class.
DI Container A component that creates objects and resolves their dependencies.

5. How the ASP.NET Core DI Container Works

ASP.NET Core provides a built-in DI container through IServiceCollection and IServiceProvider.

There are three important concepts:

  • IServiceCollection: Holds service registrations.
  • IServiceProvider: Resolves registered services and creates their dependencies.
  • ServiceDescriptor: Represents a service registration, including its service type, implementation, and lifetime.

Typical DI Flow

1. Register services
       |
       v
2. Build the application host
       |
       v
3. DI container creates IServiceProvider
       |
       v
4. A controller or service is requested
       |
       v
5. Container checks its dependencies
       |
       v
6. Container creates required objects
       |
       v
7. Dependencies are injected into the constructor

Example

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<ProductService>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();

When ASP.NET Core creates a ProductsController, it resolves ProductService. ProductService requires IProductRepository, so the container resolves the registered ProductRepository implementation.

6. Service Registration and Resolution

Service registration tells the DI container how to create a particular service.

Registrations are usually performed in Program.cs or in extension methods called from it.

6.1 Register an Interface with an Implementation

builder.Services.AddScoped<IProductService, ProductService>();

When IProductService is requested, the container creates or returns a ProductService according to the registered lifetime.

6.2 Register a Concrete Class

builder.Services.AddScoped<ProductService>();

This registration allows ProductService to be resolved directly.

6.3 Register Multiple Implementations

builder.Services.AddScoped<INotificationService, EmailNotificationService>();
builder.Services.AddScoped<INotificationService, SmsNotificationService>();

When a single INotificationService is requested, the default Microsoft DI container resolves the last registered implementation.

When IEnumerable<INotificationService> is requested, it provides all registered implementations.

public class NotificationManager
{
    private readonly IEnumerable<INotificationService> _services;
    public NotificationManager(
        IEnumerable<INotificationService> services)
    {
        _services = services;
    }
    public async Task NotifyAsync(string message)
    {
        foreach (var service in _services)
        {
            await service.SendAsync(message);
        }
    }
}

7. Three Dependency Injection Lifetimes

ASP.NET Core provides three main service lifetimes:

  1. Transient.
  2. Scoped.
  3. Singleton.

The lifetime determines how long an instance remains available and when a new instance is created.

7.1 Transient Lifetime

A Transient service creates a new instance every time the service is requested from the container.

Registration:

builder.Services.AddTransient<IEmailService, EmailService>();

Example:

public interface IOperationService
{
    Guid GetOperationId();
}
public class OperationService : IOperationService
{
    private readonly Guid _id = Guid.NewGuid();
    public Guid GetOperationId()
    {
        return _id;
    }
}

Register it as Transient:

builder.Services.AddTransient<IOperationService, OperationService>();

When requested multiple times, each resolution creates a different instance.

var first = provider.GetRequiredService<IOperationService>();
var second = provider.GetRequiredService<IOperationService>();
Console.WriteLine(first.GetOperationId());
Console.WriteLine(second.GetOperationId());

The two IDs will normally be different.

Typical use cases:

  • Lightweight stateless services.
  • Small calculation services.
  • Data transformation services.
  • Services that do not need to preserve state between resolutions.

Important: Transient does not mean the object is destroyed immediately after a method finishes. When the container creates a disposable transient service, it tracks it for disposal with the scope that created it.

7.2 Scoped Lifetime

A Scoped service creates one instance per DI scope.

In a typical ASP.NET Core Web API, each HTTP request has its own scope.

If the same scoped service is requested multiple times within the same request scope, the same instance is returned.

Registration:

builder.Services.AddScoped<IProductRepository, ProductRepository>();

Example:

builder.Services.AddScoped<IOperationService, OperationService>();

Suppose two services request IOperationService within the same HTTP request.

public class ServiceA
{
    public ServiceA(IOperationService operation)
    {
        Console.WriteLine(operation.GetOperationId());
    }
}
public class ServiceB
{
    public ServiceB(IOperationService operation)
    {
        Console.WriteLine(operation.GetOperationId());
    }
}

Both services receive the same instance because they are resolved within the same scope.

For a second HTTP request, a new scoped instance is created.

Typical use cases:

  • Entity Framework Core DbContext.
  • Repository services.
  • Unit of Work implementations.
  • Request-specific business services.
  • Services that maintain state for one request.

Important: Scoped does not always mean one instance per HTTP request. It means one instance per DI scope. Applications can create additional scopes, such as for background processing.

7.3 Singleton Lifetime

A Singleton service creates one instance for the lifetime of the root service provider.

The same instance is shared whenever the service is requested from that provider or its child scopes.

Registration:

builder.Services.AddSingleton<ICacheService, CacheService>();

Example:

public class CacheService : ICacheService
{
    private readonly Dictionary<string, string> _cache = new();
    public void Set(string key, string value)
    {
        _cache[key] = value;
    }
    public string? Get(string key)
    {
        return _cache.TryGetValue(key, out var value)
            ? value
            : null;
    }
}

All consumers receive the same CacheService instance.

Typical use cases:

  • Thread-safe in-memory caches.
  • Stateless shared services.
  • Application-wide configuration services.
  • Shared metadata providers.

Important: Singleton services are shared across concurrent requests. They must be designed to handle concurrent access safely. A Singleton should not store request-specific user or tenant state in ordinary instance fields.

8. Lifetime Comparison and Examples

Feature Transient Scoped Singleton
Instance creation Every resolution Once per scope Once per root provider
Same instance within one request Not guaranteed Yes Yes
Shared across HTTP requests No No Yes
Typical usage Lightweight services DbContext and repositories Shared caches

Visual Example

HTTP Request 1
|
+-- Transient A  (Instance T1)
+-- Transient B  (Instance T2)
+-- Scoped A     (Instance S1)
+-- Scoped B     (Instance S1)
+-- Singleton    (Instance G1)
HTTP Request 2
|
+-- Transient A  (Instance T3)
+-- Transient B  (Instance T4)
+-- Scoped A     (Instance S2)
+-- Scoped B     (Instance S2)
+-- Singleton    (Instance G1)

Notice:

  • Transient instances are different for separate resolutions.
  • Scoped instances are shared within one scope but differ across scopes.
  • Singleton instances are shared across all scopes created by the same root provider.

How to Demonstrate Lifetimes

Register three services:

builder.Services.AddTransient<TransientOperation>();
builder.Services.AddScoped<ScopedOperation>();
builder.Services.AddSingleton<SingletonOperation>();

Each class can expose a unique ID:

public class TransientOperation
{
    public Guid Id { get; } = Guid.NewGuid();
}
public class ScopedOperation
{
    public Guid Id { get; } = Guid.NewGuid();
}
public class SingletonOperation
{
    public Guid Id { get; } = Guid.NewGuid();
}

Inject each service into two different consumers and compare the IDs. The results demonstrate how each lifetime behaves.

9. Captive Dependencies

A Captive Dependency occurs when a service with a longer lifetime holds a dependency with a shorter lifetime, causing the shorter-lived dependency to effectively live longer than intended.

Example: Singleton Depending on Scoped Service

builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddSingleton<ReportService>();
public class ReportService
{
    private readonly IUserService _userService;
    public ReportService(IUserService userService)
    {
        _userService = userService;
    }
}

This is an incorrect lifetime combination.

ReportService is Singleton, but IUserService is Scoped.

The Singleton may retain the same scoped instance beyond the intended scope.

With scope validation enabled, the built-in container can detect this problem and throw an exception.

Why Is It Dangerous?

  • Request-specific data may be shared across requests.
  • Scoped objects may remain alive longer than intended.
  • Entity Framework Core DbContext may be used incorrectly.
  • Concurrent requests may access shared state unexpectedly.
  • Memory usage and resource management may become problematic.

Correct Approaches

Option 1: Change the Singleton to Scoped

builder.Services.AddScoped<ReportService>();

This is the simplest solution when the service is request-specific.

Option 2: Create a Scope When Needed

If the service genuinely needs to remain Singleton, it can use IServiceScopeFactory to create a separate scope when it needs a scoped dependency.

public class ReportService
{
    private readonly IServiceScopeFactory _scopeFactory;
    public ReportService(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }
    public async Task GenerateAsync()
    {
        using var scope = _scopeFactory.CreateScope();
        var userService = scope.ServiceProvider
            .GetRequiredService<IUserService>();
        // Use the scoped service within this scope.
        await Task.CompletedTask;
    }
}

The scoped service must not be retained after the scope is disposed.

10. Scopes and IServiceScopeFactory

A DI scope is a boundary that controls the lifetime of scoped services and tracks disposable services created within that scope.

ASP.NET Core automatically creates a scope for each HTTP request.

However, scopes can also be created manually.

Example: Create a Manual Scope

using var scope = serviceProvider.CreateScope();
var service = scope.ServiceProvider
    .GetRequiredService<IProductService>();
await service.ProcessAsync();

When the scope is disposed, scoped services and other disposable services tracked by that scope are disposed.

Create a Scope Using IServiceScopeFactory

public class DataProcessor
{
    private readonly IServiceScopeFactory _scopeFactory;
    public DataProcessor(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }
    public async Task ProcessAsync()
    {
        using var scope = _scopeFactory.CreateScope();
        var repository = scope.ServiceProvider
            .GetRequiredService<IProductRepository>();
        var products = await repository.GetAllAsync();
        // Process products inside this scope.
    }
}

This approach is particularly useful when a Singleton service or background worker needs to use scoped dependencies.

11. Constructor Injection

Constructor Injection is the most commonly recommended DI technique in ASP.NET Core.

Dependencies are provided through the class constructor.

public class OrderService
{
    private readonly IOrderRepository _repository;
    private readonly ILogger<OrderService> _logger;
    public OrderService(
        IOrderRepository repository,
        ILogger<OrderService> logger)
    {
        _repository = repository;
        _logger = logger;
    }
}

Advantages:

  • Dependencies are explicit.
  • Required dependencies are available when the object is created.
  • Dependencies can be stored in readonly fields.
  • Unit testing becomes easier.
  • Classes are easier to understand.

Constructor Injection and Optional Dependencies

Required dependencies should normally be constructor parameters.

Optional behavior should be modeled explicitly rather than relying on a large constructor containing many nullable dependencies.

12. Other Injection Techniques

12.1 Property Injection

Property Injection supplies dependencies through public or writable properties.

public class OrderService
{
    public IEmailService? EmailService { get; set; }
}

The default ASP.NET Core DI container does not automatically perform general property injection.

It is usually better to use constructor injection because property injection can leave required dependencies uninitialized.

12.2 Method Injection

Method Injection supplies a dependency as a method parameter.

public class ReportService
{
    public void Generate(IReportFormatter formatter)
    {
        formatter.Format();
    }
}

This is useful when a dependency is needed only for a particular operation.

12.3 Action Method Injection

ASP.NET Core MVC supports action method injection through the [FromServices] attribute.

[HttpGet]
public IActionResult Get(
    [FromServices] IProductService productService)
{
    return Ok(productService.GetProducts());
}

This is useful for dependencies required by only one action, but constructor injection is generally preferable for dependencies that are central to the controller.

13. Advanced Service Registration

13.1 Register an Existing Instance

You can register an already-created object as a Singleton instance.

var configuration = new AppConfiguration
{
    ApplicationName = "MyApp"
};
builder.Services.AddSingleton(configuration);

The DI container uses the supplied instance. The application is responsible for its creation and should account for its disposal if it implements IDisposable.

13.2 Register Multiple Interfaces for One Implementation

Suppose a class implements two interfaces.

public class NotificationService :
    IEmailService,
    ISmsService
{
}

To ensure both interfaces resolve to the same scoped instance, register the concrete class once and map both interfaces to it:

builder.Services.AddScoped<NotificationService>();
builder.Services.AddScoped<IEmailService>(
    sp => sp.GetRequiredService<NotificationService>());
builder.Services.AddScoped<ISmsService>(
    sp => sp.GetRequiredService<NotificationService>());

Simply registering the implementation separately for each interface can create separate instances when using Transient or Scoped lifetimes.

13.3 Conditional Registration

Different implementations can be registered based on configuration or environment.

if (builder.Environment.IsDevelopment())
{
    builder.Services.AddScoped<IPaymentService, FakePaymentService>();
}
else
{
    builder.Services.AddScoped<IPaymentService, PaymentService>();
}

This is useful for selecting development, testing, and production implementations.

13.4 TryAdd Registration

TryAdd methods from Microsoft.Extensions.DependencyInjection.Extensions register a service only if a matching registration does not already exist.

using Microsoft.Extensions.DependencyInjection.Extensions;
builder.Services.TryAddScoped<IProductService, ProductService>();

This is useful when building reusable libraries that should provide defaults without overriding registrations supplied by the application.

13.5 Replace and Remove Registrations

In integration tests or application configuration, an existing registration can be replaced.

builder.Services.RemoveAll<IEmailService>();
builder.Services.AddSingleton<IEmailService, FakeEmailService>();

RemoveAll is available through the dependency injection extension methods namespace. It removes all registrations for the specified service type.

14. Open Generic Registrations

Open Generic Registration allows the DI container to resolve generic interfaces for different type arguments without registering every closed generic type separately.

Example

Define a generic repository interface:

public interface IRepository<T>
{
    Task<T?> GetByIdAsync(int id);
    Task AddAsync(T entity);
}

Create a generic implementation:

public class Repository<T> : IRepository<T>
{
    public Task<T?> GetByIdAsync(int id)
    {
        // Data access implementation.
        return Task.FromResult(default(T));
    }
    public Task AddAsync(T entity)
    {
        // Data access implementation.
        return Task.CompletedTask;
    }
}

Register the open generic types:

builder.Services.AddScoped(
    typeof(IRepository<>),
    typeof(Repository<>));

Now the container can resolve:

IRepository<Product>
IRepository<Customer>
IRepository<Order>

The DI container constructs the corresponding closed generic implementation when requested.

15. Keyed Services in .NET

Keyed Services allow multiple implementations of the same service interface to be registered with different keys.

This feature is available in modern .NET versions, beginning with .NET 8.

Example

Define an interface:

public interface INotificationService
{
    Task SendAsync(string message);
}

Create two implementations:

public class EmailNotificationService : INotificationService
{
    public Task SendAsync(string message)
    {
        return Task.CompletedTask;
    }
}
public class SmsNotificationService : INotificationService
{
    public Task SendAsync(string message)
    {
        return Task.CompletedTask;
    }
}

Register them with keys:

builder.Services.AddKeyedScoped<INotificationService,
    EmailNotificationService>("email");
builder.Services.AddKeyedScoped<INotificationService,
    SmsNotificationService>("sms");

Resolve the required implementation:

public class NotificationController : ControllerBase
{
    private readonly INotificationService _emailService;
    private readonly INotificationService _smsService;
    public NotificationController(
        [FromKeyedServices("email")]
        INotificationService emailService,
        [FromKeyedServices("sms")]
        INotificationService smsService)
    {
        _emailService = emailService;
        _smsService = smsService;
    }
}

Keyed Services are useful when multiple implementations exist and the consumer must select one based on a known key.

16. Options Pattern

The Options Pattern is used to access strongly typed application configuration through Dependency Injection.

Instead of reading configuration values directly throughout the application, configuration can be mapped to a class and injected into services.

Step 1: Define Configuration

{
    "EmailSettings": {
        "Host": "smtp.example.com",
        "Port": 587,
        "Sender": "noreply@example.com"
    }
}

Step 2: Create a Settings Class

public class EmailSettings
{
    public string Host { get; set; } = string.Empty;
    public int Port { get; set; }
    public string Sender { get; set; } = string.Empty;
}

Step 3: Register Configuration

builder.Services.Configure<EmailSettings>(
    builder.Configuration.GetSection("EmailSettings"));

Step 4: Inject IOptions

using Microsoft.Extensions.Options;
public class EmailService
{
    private readonly EmailSettings _settings;
    public EmailService(IOptions<EmailSettings> options)
    {
        _settings = options.Value;
    }
    public void DisplayConfiguration()
    {
        Console.WriteLine(_settings.Host);
        Console.WriteLine(_settings.Port);
    }
}

Different Options Interfaces

Interface Behavior Typical Usage
IOptions<T> Provides a stable options value and does not automatically reload it for each access. Configuration that does not need to be refreshed.
IOptionsSnapshot<T> Provides options evaluated for a scope. Request-scoped configuration in web applications.
IOptionsMonitor<T> Supports monitoring updated options values when the configuration provider supports reload. Long-lived services that need to observe configuration changes.

Important: IOptionsSnapshot is scoped and should not be injected directly into a Singleton. IOptionsMonitor is suitable for Singleton consumers that need to observe updated configuration.

17. Factory-Based Registrations

Sometimes, creating a service requires custom logic or configuration values.

In such situations, use factory-based registration.

Example

builder.Services.AddScoped<IProductService>(serviceProvider =>
{
    var repository = serviceProvider
        .GetRequiredService<IProductRepository>();
    var logger = serviceProvider
        .GetRequiredService<ILogger<ProductService>>();
    return new ProductService(repository, logger);
});

The factory receives an IServiceProvider and creates the implementation.

When to Use Factory Registration

  • When construction requires custom logic.
  • When an implementation depends on configuration.
  • When selecting an implementation based on a condition.
  • When integrating with third-party libraries.

Avoid using service-provider lookups throughout ordinary business classes. Constructor injection should remain the default.

18. Service Disposal and Cleanup

Some services allocate resources that must be released when they are no longer needed.

Examples include:

  • Database connections.
  • File streams.
  • Network resources.
  • Native operating system handles.

.NET provides two common cleanup interfaces:

  • IDisposable: Synchronous cleanup through Dispose().
  • IAsyncDisposable: Asynchronous cleanup through DisposeAsync().

Example

public class FileProcessor : IDisposable
{
    private readonly FileStream _stream;
    public FileProcessor(string path)
    {
        _stream = File.OpenRead(path);
    }
    public void Dispose()
    {
        _stream.Dispose();
    }
}

When the DI container creates a disposable service, it tracks it and disposes it when its owning scope or provider is disposed.

Important best practices:

  • Do not manually dispose a service that is owned by the DI container.
  • Do not register a disposable scoped service as Singleton without carefully considering its lifetime.
  • Dispose manually created resources that are not owned by the DI container.
  • Use await using when working with an asynchronously disposable scope or resource.

19. Dependency Injection in Middleware

ASP.NET Core middleware components participate in the HTTP request pipeline.

Conventional middleware is generally constructed once when the application pipeline is built. Therefore, injecting a Scoped service directly into its constructor can cause a lifetime problem.

Incorrect Example

public class CustomMiddleware
{
    private readonly IUserService _userService;
    public CustomMiddleware(
        RequestDelegate next,
        IUserService userService)
    {
        _userService = userService;
    }
}

If IUserService is Scoped, this constructor injection is invalid for conventional middleware.

Correct Approach: Inject into InvokeAsync

public class CustomMiddleware
{
    private readonly RequestDelegate _next;
    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(
        HttpContext context,
        IUserService userService)
    {
        var user = await userService.GetCurrentUserAsync();
        await _next(context);
    }
}

ASP.NET Core resolves the method-injected service from the current request scope.

Register the middleware:

app.UseMiddleware<CustomMiddleware>();

Alternative: Use IMiddleware when you want middleware itself to be activated through DI and use its registered lifetime.

20. Dependency Injection in Background Services

Background services generally run as Singleton services.

They should not directly inject Scoped services such as DbContext into their constructors.

Incorrect Example

public class ProductWorker : BackgroundService
{
    private readonly AppDbContext _context;
    public ProductWorker(AppDbContext context)
    {
        _context = context;
    }
    protected override Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        return Task.CompletedTask;
    }
}

AppDbContext is usually Scoped, while the hosted service is Singleton. This creates a lifetime mismatch.

Correct Example Using IServiceScopeFactory

public class ProductWorker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<ProductWorker> _logger;
    public ProductWorker(
        IServiceScopeFactory scopeFactory,
        ILogger<ProductWorker> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await using var scope = _scopeFactory.CreateAsyncScope();
                var repository = scope.ServiceProvider
                    .GetRequiredService<IProductRepository>();
                var products = await repository.GetAllAsync();
                _logger.LogInformation(
                    "Processed {Count} products.",
                    products.Count);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    exception,
                    "Product processing failed.");
            }
            await Task.Delay(
                TimeSpan.FromMinutes(1),
                stoppingToken);
        }
    }
}

Register the worker:

builder.Services.AddHostedService<ProductWorker>();

Each iteration creates a new scope. The scoped repository and its dependencies are disposed when that scope ends.

21. Third-Party Dependency Injection Containers

ASP.NET Core provides a built-in DI container that is sufficient for most applications.

However, some enterprise applications may use third-party containers when they require additional features.

Examples include:

  • Autofac.
  • DryIoc.
  • Simple Injector.

Depending on the container, additional capabilities may include advanced registration rules, decorators, modules, and more complex object composition.

Use the built-in container unless a specific requirement justifies introducing another dependency injection framework.

22. Testing Services with Dependency Injection

Dependency Injection makes it easier to test a class by replacing its real dependencies with mocks or fake implementations.

Example

Service:

public class ProductService
{
    private readonly IProductRepository _repository;
    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
    public async Task<string> GetProductNameAsync(int id)
    {
        var product = await _repository.GetByIdAsync(id);
        return product?.Name ?? "Not Found";
    }
}

Test using a mock:

[Fact]
public async Task GetProductName_ShouldReturnName()
{
    var repository = new Mock<IProductRepository>();
    repository
        .Setup(x => x.GetByIdAsync(1))
        .ReturnsAsync(new Product("Laptop", 50000));
    var service = new ProductService(repository.Object);
    var result = await service.GetProductNameAsync(1);
    Assert.Equal("Laptop", result);
}

The test does not need SQL Server because the repository dependency is replaced with a mock.

Testing DI Registrations

Integration tests can also verify that the application container is configured correctly.

using var scope = app.Services.CreateScope();
var productService = scope.ServiceProvider
    .GetRequiredService<IProductService>();
Assert.NotNull(productService);

In real integration tests, use the test host or WebApplicationFactory to create an isolated application environment.

23. Performance Considerations

Dependency Injection itself is usually not a major performance bottleneck in typical ASP.NET Core applications. However, poor registration and object-lifetime decisions can create unnecessary allocations or resource usage.

Important Considerations

  • Use Singleton for suitable shared services instead of repeatedly creating expensive objects.
  • Use Scoped for request-specific services and DbContext.
  • Use Transient for lightweight services that do not require shared state.
  • Avoid resolving large object graphs unnecessarily.
  • Avoid service locator patterns throughout application code.
  • Do not use Singleton as a shortcut for caching without considering thread safety and memory management.
  • Use appropriate pooling features, such as DbContext pooling, only after understanding their lifecycle and state-reset requirements.

DbContext Pooling

Entity Framework Core supports DbContext pooling, which reuses context instances to reduce allocation overhead.

builder.Services.AddDbContextPool<AppDbContext>(
    options =>
        options.UseSqlServer(
            builder.Configuration.GetConnectionString("DefaultConnection")));

DbContext pooling is not the same as registering DbContext as a Singleton. Pooled contexts are leased for use and returned to the pool when disposed.

Do not store request-specific state in a pooled DbContext unless it is reliably reset between uses.

24. Dependency Injection Best Practices

  1. Prefer constructor injection: Make required dependencies explicit.
  2. Depend on abstractions: Use interfaces where they provide meaningful flexibility.
  3. Choose lifetimes carefully: Understand Transient, Scoped, and Singleton behavior.
  4. Avoid captive dependencies: Do not inject Scoped services directly into Singleton services.
  5. Keep Singleton services thread-safe: They are shared across concurrent requests.
  6. Use Scoped for DbContext: The normal EF Core registration is request-scoped.
  7. Use IServiceScopeFactory when necessary: Create scopes for background or Singleton workflows that need scoped services.
  8. Avoid unnecessary interfaces: Do not create abstractions without a useful reason.
  9. Avoid service locator patterns: Do not repeatedly call GetRequiredService inside business classes.
  10. Use extension methods: Organize registrations by application layer or feature.
  11. Use Options Pattern: Access configuration through strongly typed options.
  12. Keep constructors simple: A class with too many dependencies may have too many responsibilities.
  13. Dispose resources correctly: Respect the DI container's ownership of disposable services.
  14. Enable scope validation: Detect lifetime mismatches during development and testing.

Organizing Registrations with Extension Methods

Instead of registering every service in Program.cs, each project can expose an extension method.

Application project:

public static class DependencyInjection
{
    public static IServiceCollection AddApplication(
        this IServiceCollection services)
    {
        services.AddScoped<ProductService>();
        return services;
    }
}

Infrastructure project:

public static class DependencyInjection
{
    public static IServiceCollection AddInfrastructure(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(
                configuration.GetConnectionString("DefaultConnection")));
        services.AddScoped<IProductRepository, ProductRepository>();
        return services;
    }
}

API project:

builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);

This keeps the API startup configuration clean and makes service registration easier to maintain.

Enable Scope Validation

Scope validation helps identify invalid dependency lifetime combinations.

builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes = true;
    options.ValidateOnBuild = true;
});

These checks are particularly useful during development and testing. They can reveal captive dependencies and services that cannot be constructed from their registrations.

25. Common Dependency Injection Mistakes

Mistake Problem Better Approach
Singleton depending on Scoped Scoped dependency may live too long. Change the lifetime or create a scope when needed.
Registering DbContext as Singleton DbContext is not designed for concurrent use across requests. Use Scoped registration or appropriate EF Core pooling.
Using new for every dependency Creates tight coupling and bypasses container lifetime management. Use constructor injection for managed dependencies.
Too many constructor dependencies May indicate a class has too many responsibilities. Refactor into focused services.
Capturing Scoped services in conventional middleware constructors The dependency can outlive the request scope. Inject into InvokeAsync or use IMiddleware.
Using service locator everywhere Dependencies become hidden and testing becomes harder. Prefer constructor injection.
Registering duplicate implementations unintentionally Single-service resolution may select the last registration. Use deliberate registration or keyed services.
Ignoring disposal Resources may remain open longer than intended. Respect scope ownership and disposal.

26. Interview Questions and Answers

Q1. What is Dependency Injection in ASP.NET Core?

Dependency Injection is a technique in which a class receives its required dependencies from an external container instead of creating them internally. ASP.NET Core provides a built-in DI container for registering and resolving services.

Q2. What is the difference between IoC and DI?

IoC is a broader principle that transfers control to an external mechanism. DI is a technique used to implement IoC by supplying dependencies from outside a class.

Q3. What are the three DI lifetimes in ASP.NET Core?

  • Transient: A new instance is created for every resolution.
  • Scoped: One instance is created per DI scope.
  • Singleton: One instance is shared for the lifetime of the root service provider.

Q4. What is the difference between Transient and Scoped?

Transient creates a new instance each time it is resolved. Scoped creates one instance per scope, so multiple consumers in the same HTTP request generally receive the same instance.

Q5. What is the difference between Scoped and Singleton?

Scoped creates one instance per scope, while Singleton creates one instance shared across all scopes belonging to the same root service provider.

Q6. Why is DbContext usually registered as Scoped?

DbContext represents a unit of work and is designed to be used within a short-lived scope. A request-scoped lifetime provides an appropriate boundary for database operations and avoids sharing the same context concurrently across unrelated requests.

Q7. Can a Singleton service depend on a Scoped service?

Not directly through its constructor. This creates a captive dependency. If the Singleton genuinely needs a scoped service, it should create a scope using IServiceScopeFactory and use the scoped dependency only within that scope.

Q8. What is a Captive Dependency?

A Captive Dependency occurs when a longer-lived service holds a shorter-lived dependency, causing the shorter-lived object to remain alive longer than intended.

Q9. What is IServiceCollection?

IServiceCollection is a collection of service registrations. It is used to register service types, implementations, factories, and lifetimes.

Q10. What is IServiceProvider?

IServiceProvider resolves registered services and creates the required dependency graph.

Q11. What is IServiceScopeFactory?

IServiceScopeFactory creates new DI scopes. It is commonly used in background services and Singleton services that need access to Scoped dependencies.

Q12. Why is constructor injection preferred?

Constructor injection makes dependencies explicit, ensures required dependencies are supplied during object creation, and makes unit testing easier.

Q13. Does ASP.NET Core support property injection by default?

The built-in DI container does not automatically support general property injection. Constructor injection is the usual approach.

Q14. What happens when multiple implementations of an interface are registered?

When a single service is requested, the default Microsoft DI container returns the last registered implementation. When IEnumerable of that interface is requested, it returns all registered implementations.

Q15. What are Open Generic Registrations?

Open Generic Registrations allow a generic interface and generic implementation to be registered once and resolved for multiple type arguments.

Q16. What are Keyed Services?

Keyed Services allow multiple implementations of the same service type to be registered with different keys. A consumer can request a particular implementation by specifying its key.

Q17. What is the Options Pattern?

The Options Pattern maps configuration values to strongly typed classes and makes them available through DI using interfaces such as IOptions, IOptionsSnapshot, and IOptionsMonitor.

Q18. What is the difference between IOptions and IOptionsSnapshot?

IOptions provides a stable options value, while IOptionsSnapshot provides options evaluated for a DI scope. IOptionsSnapshot is scoped and is useful for request-specific configuration evaluation.

Q19. What is the difference between IOptionsSnapshot and IOptionsMonitor?

IOptionsSnapshot is scoped and provides a value for the current scope. IOptionsMonitor supports observing updated options values and can be injected into Singleton services.

Q20. How do you inject a Scoped service into middleware?

For conventional middleware, inject the Scoped service into the Invoke or InvokeAsync method rather than the middleware constructor. Alternatively, implement IMiddleware and register it through DI.

Q21. How do you use Scoped services in a BackgroundService?

Inject IServiceScopeFactory, create a scope during processing, resolve the Scoped service from that scope, and dispose the scope when processing is complete.

Q22. Does the DI container dispose registered services?

Yes. The container tracks disposable services it creates and disposes them when their owning scope or provider is disposed. Objects supplied as pre-created instances are generally owned and disposed by the code that created them.

Q23. What is the Service Locator Pattern?

Service Locator is a pattern in which a class requests dependencies from a central provider instead of declaring them as constructor parameters. It can hide dependencies and make testing more difficult, so constructor injection is generally preferred.

Q24. Can we register multiple services with the same interface?

Yes. Multiple implementations can be registered. Resolve a single implementation when appropriate, use IEnumerable to obtain all registrations, or use Keyed Services when a specific implementation must be selected.

Q25. What is the difference between AddSingleton and AddSingleton with an instance?

AddSingleton with an implementation type or factory asks the container to create and manage the service instance. AddSingleton with an existing instance registers an object that has already been created, and its creator remains responsible for its disposal.

Q26. What is DbContext Pooling?

DbContext pooling reuses DbContext instances to reduce allocation overhead. It does not make DbContext a Singleton; a context is leased for use and returned to the pool when disposed.

Q27. When would you use Transient, Scoped, and Singleton?

  • Transient for lightweight services that do not need shared state.
  • Scoped for request-level services, repositories, and DbContext.
  • Singleton for suitable shared services that are thread-safe and do not hold request-specific state.

27. Summary

Dependency Injection is an essential feature of ASP.NET Core that helps build loosely coupled, maintainable, and testable applications.

  • IoC: A principle that transfers control to an external mechanism.
  • DI: Supplies dependencies from outside a class.
  • Transient: Creates a new instance for each resolution.
  • Scoped: Creates one instance per scope.
  • Singleton: Shares one instance across the root service provider's lifetime.
  • IServiceCollection: Stores service registrations.
  • IServiceProvider: Resolves services and their dependencies.
  • IServiceScopeFactory: Creates scopes for Scoped services.
  • Constructor Injection: The preferred way to provide required dependencies.
  • Options Pattern: Provides strongly typed configuration.
  • Keyed Services: Select between multiple implementations using keys.

28. Conclusion

Understanding Dependency Injection goes beyond knowing how to register services with AddTransient, AddScoped, and AddSingleton.

Developers must understand object lifetimes, scope boundaries, disposal, thread safety, factory registrations, and dependency relationships.

Correct DI design prevents common problems such as captive dependencies, incorrect DbContext usage, unnecessary object creation, and hidden dependencies.

The most important principle: Register each service with a lifetime that matches how it is used, keep dependencies explicit, and allow the DI container to manage object creation and cleanup.

🔙
Clean Architecture in ASP.NET Core :👈 👉:Middleware Explained