SkillPilotAI

Dependency Injection

Dependency Injection (DI) means a class asks for what it needs through its constructor and a container creates and supplies those objects. ASP.NET Core has a DI container built in: you register services in builder.Services, choose a lifetime, and the framework builds the whole object graph for you.

39.1 Why is it used?

  • Creating objects with new inside endpoints gives a fresh object every time, so shared state (an order list) is lost.
  • new ties code to a concrete class (SmsNotifier); switching to WhatsApp or a fake in tests means editing every caller.
  • DI puts object creation and lifetime in one place (Program.cs).
  • Classes depend on abstractions (INotifier), which makes them easy to swap and unit test.

39.2 The bug: new everywhere

  • POST creates its own OrderStore and places a Masala Dosa order; GET creates a different new OrderStore.
  • Result: the order is placed, but the list is empty.
C#
var builder = WebApplication.CreateBuilder(args);var app = builder.Build(); app.MapPost("/orders", () =>{    var service = new OrderService(        new OrderStore(), new SmsNotifier());    return service.Place("Masala Dosa");}); app.MapGet("/orders", () =>    new OrderStore().All()); app.Run();
Output
$ curl -i localhost:5039/ordersHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8[]
Why did the order disappear?
  1. 1.POST: new OrderStore() #1, order added there

  2. 2.GET: new OrderStore() #2, a different empty object

  3. 3.GET returns []

  4. 4.Also: endpoint hard-wired to concrete SmsNotifier

  5. 5.Fix: let the DI container create objects and decide lifetime

Creating objects and their lifetime: one place

39.3 Fix: register services

  • AddSingleton<OrderStore>(): one object for the whole app, so POST and GET share it.
  • AddScoped<OrderService>(): one per HTTP request.
  • AddTransient<INotifier, SmsNotifier>(): whoever asks for INotifier gets an SmsNotifier.
  • Endpoints just declare parameters (OrderService service); the container supplies them.
C#
var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton<OrderStore>();builder.Services.AddScoped<OrderService>();builder.Services.AddTransient<INotifier,    SmsNotifier>(); var app = builder.Build(); app.MapPost("/orders", (OrderService service)    => service.Place("Masala Dosa"));app.MapGet("/orders", (OrderStore store)    => store.All()); app.Run();
Output
$ curl -X POST localhost:5039/ordersSMS: Order 1 placed: Masala Dosa$ curl -X POST localhost:5039/ordersSMS: Order 2 placed: Masala Dosa$ curl localhost:5039/orders[{"id":1,"item":"Masala Dosa"}, {"id":2,"item":"Masala Dosa"}]

39.4 Constructor injection

  • OrderService asks for OrderStore and INotifier in its (primary) constructor.
  • The container reads the parameters, creates OrderStore and SmsNotifier first, then OrderService.
  • OrderService does not know whether the notifier is SMS or WhatsApp: switching is one line in Program.cs.
C#
public class OrderService(    OrderStore store, INotifier notifier){    public string Place(string item)    {        var order = store.Add(item);        return notifier.Send(            $"Order {order.Id} placed: {item}");    }}
How the container builds the object graph
  1. 1.Request needs OrderService (endpoint parameter)

  2. 2.Container reads its constructor: OrderStore, INotifier

  3. 3.OrderStore: singleton, reuse the existing one

  4. 4.INotifier: transient, create a new SmsNotifier

  5. 5.Create OrderService with both and call the handler

39.5 The three lifetimes

  • Each class gets a random 4-character Id when created; the endpoint asks for transient and scoped twice.
  • Transient: the two Ids always differ. Scoped: same within one request, new in the next. Singleton: 9806 in both requests.
C#
builder.Services.AddTransient<TransientOp>();builder.Services.AddScoped<ScopedOp>();builder.Services.AddSingleton<SingletonOp>(); app.MapGet("/ids", (    TransientOp t1, TransientOp t2,    ScopedOp s1, ScopedOp s2,    SingletonOp g) => new{    transient = $"{t1.Id} {t2.Id}",    scoped = $"{s1.Id} {s2.Id}",    singleton = g.Id});
Output
$ curl localhost:5039/ids{"transient":"1d29 5052","scoped":"1771 1771", "singleton":"9806"}$ curl localhost:5039/ids{"transient":"0825 f3af","scoped":"2e1d 2e1d", "singleton":"9806"}
LifetimeRegister withOne object perTypical use
TransientAddTransientEvery resolutionSmall stateless helpers
ScopedAddScopedHTTP requestDbContext, per-request services
SingletonAddSingletonWhole appCaches, config; must be thread safe

39.6 Captive dependency

  • A singleton (PriceCache) asks for a scoped service (ProductDb, like an EF Core DbContext).
  • The singleton lives forever, so the scoped object inside it is captured and also lives forever.
  • In Development, scope validation stops the app at Build() with a clear error.
C#
// Program.csbuilder.Services.AddScoped<ProductDb>();builder.Services.AddSingleton<PriceCache>();// ...app.MapGet("/db", (PriceCache cache)    => cache.DbId); // PriceCache.cspublic class PriceCache(ProductDb db){    public string DbId => db.Id;}
Output
$ dotnet runUnhandled exception. System.AggregateException:Some services are not able to be constructed ... ---> System.InvalidOperationException:Cannot consume scoped service 'ProductDb'from singleton 'PriceCache'.   at ...WebApplicationBuilder.Build()
  • Checkpoint: in Production scope validation is off by default, so the app starts.
  • But both requests return the same Id db0c: every request shares one old ProductDb (stale data, thread-safety bugs).
Output
$ dotnet run -- --environment Productioninfo: Microsoft.Hosting.Lifetime[0]      Hosting environment: Production$ curl localhost:5039/dbdb0c$ curl localhost:5039/dbdb0c
Captive dependency and its fix
  1. 1.PriceCache registered as singleton

  2. 2.Its constructor takes scoped ProductDb

  3. 3.ProductDb now lives as long as the app (captured)

  4. 4.Development: Build() throws; Production: same db0c every request

  5. 5.Fix: inject IServiceScopeFactory, CreateScope per call

A longer life must not hold a shorter one

39.7 Fix: IServiceScopeFactory

  • IServiceScopeFactory is itself a singleton, so a singleton may depend on it.
  • On each call CreateScope() gives a new scope and GetRequiredService<ProductDb>() a fresh instance.
  • using disposes the scope (and the ProductDb) when the work is done: each call gets a new Id.
  • The same pattern is used in background jobs (hosted services).
C#
public class PriceCache(    IServiceScopeFactory scopes){    public string DbId()    {        using var scope = scopes.CreateScope();        var db = scope.ServiceProvider            .GetRequiredService<ProductDb>();        return db.Id;    }} // GET /db: dff3, then 1a63

39.8 Multiple implementations and keyed services

  • Two registrations for INotifier: asking for one INotifier gives the last registration (WhatsApp).
  • IEnumerable<INotifier> gives all of them in registration order: useful to send SMS and WhatsApp together.
  • Keyed services (.NET 8): AddKeyedSingleton<IPaymentGateway, UpiGateway>("upi") registers by key.
  • [FromKeyedServices("upi")] injects exactly that implementation.
C#
builder.Services.AddTransient<INotifier,    SmsNotifier>();builder.Services.AddTransient<INotifier,    WhatsAppNotifier>(); var app = builder.Build(); app.MapGet("/notify", (INotifier one,    IEnumerable<INotifier> all) => new{    one = one.Send("Hi"),    all = all.Select(n => n.Send("Hi"))});
Output
$ curl localhost:5039/notify{"one":"WhatsApp: Hi", "all":["SMS: Hi","WhatsApp: Hi"]}
C#
var builder = WebApplication.CreateBuilder(args); builder.Services.AddKeyedSingleton<    IPaymentGateway, UpiGateway>("upi");builder.Services.AddKeyedSingleton<    IPaymentGateway, CardGateway>("card"); var app = builder.Build(); app.MapPost("/pay/upi", (    [FromKeyedServices("upi")]    IPaymentGateway gateway)    => gateway.Pay(499)); app.Run();
Output
$ curl -i -X POST localhost:5039/pay/upiHTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8UPI paid 499

39.9 Common mistakes

  • new-ing services inside classes or endpoints instead of asking for them.
  • Injecting a scoped service (DbContext) into a singleton: captive dependency.
  • Singletons with mutable state that are not thread safe.
  • Myth: scoped means per user or per login session. It means per HTTP request; the next request from the same user gets a new object.
  • Myth: DI needs an interface for every class. OrderStore and OrderService were registered as concrete classes and worked fine.

39.10 Rules

  1. Ask for dependencies through the constructor; no new for services.
  2. Choose lifetimes deliberately: DbContext scoped, shared cache singleton.
  3. Never inject scoped into singleton; use IServiceScopeFactory when needed.
  4. All implementations: IEnumerable; a specific one: keyed service.
  5. Keep singletons thread safe.

39.11 Interview tips

  • DI: dependencies come through the constructor and are registered in builder.Services; the container builds the object graph.
  • Transient = new every time, scoped = one per request, singleton = one for the app.
  • Captive dependency: scoped inside singleton; scope validation catches it in Development; fix with IServiceScopeFactory.
  • Last registration wins for a single resolve; IEnumerable<T> gets all; keyed services pick one by key.