Dependency Injection (DI) in ASP.
NET Core
1. Introduction
Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between cl
2. Benefits of DI
- Promotes code reusability and testability
- Reduces class coupling
- Improves code maintainability
- Enables better separation of concerns
3. DI in ASP.NET Core
ASP.NET Core provides a built-in IoC container that supports constructor injection, method injection
4. Service Lifetimes
- Singleton: A single instance is created and shared throughout the application's lifetime.
- Scoped: A new instance is created per request.
- Transient: A new instance is created each time it is requested.
5. Example
public interface IMyService {
string GetData();
}
public class MyService : IMyService {
public string GetData() => "Hello from MyService";
}
// Registering in Startup.cs
services.AddScoped<IMyService, MyService>();
// Injecting into a controller
public class HomeController : Controller {
private readonly IMyService _service;
public HomeController(IMyService service) {
_service = service;
}
public IActionResult Index() {
var data = _service.GetData();
return View("Index", data);
}
}