Dependency Injection and Service Lifetimes
LoanService needs a database context, a clock and a logger. If it created them with new, you could never swap the real clock for a fake one in a test, and every class would repeat the setup. ASP.NET Core is built around dependency injection instead: classes ask for what they need, and a container hands it over.
The rule
Ask in the constructor, register once, choose a lifetime: singleton, scoped, transient.
A class declares its dependencies as constructor parameters, usually interfaces:
public class LoanService(LibraryDb db, IClock clock)
{
public async Task<Loan> BorrowAsync(int bookId, int memberId)
{
var loan = new Loan(bookId, memberId, due: clock.Today.AddDays(14));
db.Loans.Add(loan);
await db.SaveChangesAsync();
return loan;
}
}Program.cs registers each service once with the built-in container, Microsoft.Extensions.DependencyInjection:
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddDbContext<LibraryDb>(o => o.UseSqlite("Data Source=library.db"));
builder.Services.AddScoped<LoanService>();When a controller, endpoint or other service asks for LoanService, the container builds it and fills in its constructor — recursively.
The lifetime says how often a new instance is made:
| Lifetime | New instance… | Good for |
|---|---|---|
| Singleton | once for the whole app | stateless helpers, caches, config |
| Scoped | once per HTTP request | DbContext and services that use it |
| Transient | every time it is asked for | small, cheap, stateless objects |
AddDbContext registers the context as scoped.