Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways. Using DI, we move the creation and binding of the dependent objects outside of the class that depends on them.
The Dependency Injection pattern involves 3 types of classes.
As you can see, the injector class creates an object of the service class, and injects that object to a client object. In this way, the DI pattern separates the responsibility of creating an object of the service class out of the client class.Types of Dependency Injection
As you have seen above, the injector class injects the service (dependency) to the client (dependent). The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method.
Dependency Injection is a technique in which an object will receive other object which it depends on called dependency
There are also multiple ways to inject DI outside the Constructor
There are also following different ways to inject the DI without Controller Constructor
Method 1:
[HttpGet][Route("api/Product/GetProducts")]public IEnumerable<ProductDetail> GetProducts(){ //method 1 var services = this.HttpContext.RequestServices; var productService = (IProductService)services.GetService(typeof(IProductService)); return productService.GetProducts();}
[HttpGet]
[Route("api/Product/GetProducts")]
public IEnumerable<ProductDetail> GetProducts()
{
//method 1
var services = this.HttpContext.RequestServices;
var productService = (IProductService)services.GetService(typeof(IProductService));
return productService.GetProducts();
}
Method 2:
[HttpPost][Route("api/Product/AddProduct")]public IActionResult AddProduct(ProductDetail product){ //Method 2 var productService = (IProductService)this.HttpContext.RequestServices.GetService(typeof(IProductService)); productService.AddProduct(product); return Ok();}
[HttpPost]
[Route("api/Product/AddProduct")]
public IActionResult AddProduct(ProductDetail product)
//Method 2
var productService =
(IProductService)this.HttpContext.RequestServices.GetService(typeof(IProductService));
productService.AddProduct(product);
return Ok();
Method 3:
//Method 3public IActionResult UpdateProduct([FromServices] IProductService productService,ProductDetail product){ productService.UpdateProduct(product); return Ok();}
//Method 3
public IActionResult UpdateProduct([FromServices] IProductService productService,
ProductDetail product)
productService.UpdateProduct(product);
HaPPy Coding!
Very simple and precise answer is “Dependency Injection (DI) is a programming technique that makes a class independent of its dependencies”. That means you create an object of class whenever needed.
Check out the below link I hope it will help you.
Link: https://stackoverflow.com/questions/130794/what-is-dependency-injection