← .NET Core learning path
.NET Core · Module 5 of 10

Dependency injection

Register and inject services with the built-in container.

📖 Key ideas

  1. Register services in builder.Services: AddScoped, AddTransient, AddSingleton.
  2. Inject through constructors or minimal API parameters.
  3. Scoped: one per request; Transient: new each time; Singleton: one for app life.
  4. Program to interfaces: IEmailSender, EmailSender.
  5. DI makes testing and swapping implementations easy.
💡 Real-life example: DI is a hotel concierge: you ask for a service and the right person is sent, no need to hire them yourself.
AddScopedOne instance per request
AddTransientNew instance every time
AddSingletonOne instance for the app
Constructor injectionDependencies via constructor