ASP.NET Core Interview Question #66
How do you register multiple implementations of the same interface?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
Multiple implementations can be registered for the same service interface. When a consumer requests IEnumerable<TService>, the container supplies all registered implementations in registration order.
Detailed Explanation
Multiple implementations can be registered for the same service interface. When a consumer requests IEnumerable<TService>, the container supplies all registered implementations in registration order.
If a consumer requests only TService, the default container normally resolves the last registration for that service type. Therefore, requesting IEnumerable<T> or using keyed services is clearer when multiple implementations are intentional.
This pattern is useful for pipelines, validators, exporters, notification channels, or strategy collections.
Code Example
builder.Services.AddScoped<IReportExporter, PdfReportExporter>();
builder.Services.AddScoped<IReportExporter, CsvReportExporter>();
public class ExportService
{
private readonly IEnumerable<IReportExporter> _exporters;
public ExportService(IEnumerable<IReportExporter> exporters)
{
_exporters = exporters;
}
}