Using dependency injection in views
In this recipe, you will learn what a dependency injection is and how to use it in ASP.NET Core MVC views. We will see how to inject a list of category objects to bind a drop-down list in the AddProduct.cshtml
view.
The dependency injection mechanism lets a class get an object through the constructor parameter, instead of calling a factory method, such as the following code:
public ClassA (ClassB _object) { this.object = _object; }
Use following code instead of preceding code:
public ClassA() { this.object = FactoryClass.GetObjectB(); }
Getting ready
We will create an empty web application with ASP.NET Core MVC enabled by adding the MVC dependency into the project:
"Microsoft.AspNetCore.Mvc": "2.0.0"
How to do it...
- First, let's create the
Dto
and theViewModel
objects:
public class ProductDto { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } public class ProductViewModel { public int Id { get...