Captive Dependency in Service Lifetimes
Spot the captive dependency bug when mixing singleton and scoped service lifetimes.
Codecsharp
// Program.cs (ASP.NET Core)
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddSingleton<IOrderService, OrderService>();
public class OrderService : IOrderService
{
private readonly IOrderRepository _repo;
// OrderService is a singleton
public OrderService(IOrderRepository repo)
{
_repo = repo;
}
public void Place(Order order) => _repo.Save(order);
}What is the bug in this dependency registration/injection?