Roadmap › Modern .NET — Hosting, Configuration, DI & Deployment › Module: Hosting, Configuration, DI and Logging
Lessons in this course (9)

5. Built-in dependency injection

Intermediate★ Must knowLesson 5 of 9
csharp
builder.Services.AddTransient<IEmailBuilder, EmailBuilder>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddKeyedScoped<IPaymentGateway, RazorpayGateway>("razorpay");   // .NET 8
builder.Services.TryAddSingleton<ICache, MemoryCacheAdapter>();                   // only if not registered

public class CheckoutController([FromKeyedServices("razorpay")] IPaymentGateway gateway) : ControllerBase { }
  • Constructor injection preferred; [FromServices] for action parameters; IServiceProvider only in factories/composition roots (avoid the Service Locator anti-pattern).
  • Validation in Development catches scope problems (ValidateScopes, ValidateOnBuild).
  • Third-party containers (Autofac) plug in via UseServiceProviderFactory for features like interception/modules.