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.
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?
- Intermediate What is the Task Parallel Library (TPL) in C#?