⚙️ C# / .NET Intermediate

What is dependency injection in ASP.NET Core?

Answer

Dependency Injection (DI) is a design pattern where dependencies are provided to a class rather than the class creating them — promotes loose coupling and testability. ASP.NET Core has a built-in DI container. Register services in Program.cs: builder.Services.AddScoped<IUserService, UserService>();. Service lifetimes: Singleton: one instance per application (stateless services, cache). Scoped: one instance per HTTP request (DB contexts, unit-of-work). Transient: new instance every time requested (lightweight, stateless). Inject via constructor: public class UsersController(IUserService userService) { } (primary constructor) or traditional constructor injection. Benefits: (1) Testability — inject mock implementations in tests. (2) Loose coupling — depend on interfaces, not implementations. (3) Lifecycle management — container handles creation and disposal. (4) Configurability — swap implementations via configuration. For complex scenarios, third-party containers (Autofac, Castle Windsor) can replace the built-in container.