Junior — Middle
What methods and approaches do you know for implementing dependency injection in application controllers?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in application controllers in C# can be implemented in several ways:
- Through the constructor — the most common and recommended method. Dependencies are passed via the controller's constructor parameters.
public class MyController : Controller
{
private readonly IService _service;
public MyController(IService service)
{
_service = service;
}
public IActionResult Index()
{
// Using _service
return View();
}
}
- Through properties (Property Injection) — dependencies are set via the controller's properties. Less preferred, as dependencies may not be initialized in time.
public class MyController : Controller
{
[Inject]
public IService Service { get; set; }
}
- Through methods (Method Injection) — dependencies are passed as method parameters.
public IActionResult Index([FromServices] IService service)
{
// Using service
return View();
}
In ASP.NET Core, the built-in DI container supports all these methods, but constructor injection is the cleanest and most convenient for testing.