What is dependency injection (DI) and how does ASP.NET Core's built-in container work?
cs-mid-004
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
Dependency injection is an implementation of the Inversion of Control (IoC) principle: instead of a class creating its own dependencies, they are provided (injected) from outside. ASP.NET Core has a built-in DI container (IServiceCollection / IServiceProvider). You register services in Program.cs with AddTransient, AddScoped, or AddSingleton. Transient: new instance per injection. Scoped: same instance for the lifetime of an HTTP request. Singleton: one instance for the application lifetime. Constructor injection is preferred over property or method injection because it makes dependencies explicit and the class fails fast at construction time if something is missing. The container resolves the full dependency graph automatically.
Code example
// Registration (Program.cs)
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
builder.Services.AddSingleton<ICacheService, RedisCacheService>();
// Constructor injection (preferred)
public class OrderService
{
private readonly IOrderRepository _repo;
private readonly IEmailSender _email;
public OrderService(IOrderRepository repo, IEmailSender email)
{
_repo = repo;
_email = email;
}
public async Task PlaceOrderAsync(Order order)
{
await _repo.SaveAsync(order);
await _email.SendAsync(order.CustomerEmail, "Order confirmed");
}
}
Follow-up
What is the Captive Dependency problem — a singleton depending on a scoped service — and how does ASP.NET Core detect it?