Dependency Injection in ASP.NET Core is a fundamental concept that allows you to manage and inject dependencies into your application components. It promotes a decoupled and modular design, making your application more maintainable and testable.
Example
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<IMyService, MyService>();
}// MyController.cs
public class MyController : Controller
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
} // ...
}
Built-in IoC Container
ASP.NET Core comes with a built-in Inversion of Control (IoC) container that simplifies dependency injection. It provides a container for managing and resolving application services.
Example
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<IMyService, MyService>();
}
// MyController.cs
public class MyController : Controller
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
// ...
}
Registering Application Service
To register an application service for dependency injection, you can use the IServiceCollection in the ConfigureServices method of the Startup class.
ASP.NET Core provides different service lifetimes like Singleton, Transient, and Scoped to control how instances of a service are created and managed throughout the application's lifetime.