How to use dependency injection in ASP.Net Core 3.1

When classes collaborate with each other-or, more precisely, when we use composition between two classes (when class B is the property of class A)-we say that we have strongly coupled objects, which is a bad practice in object-oriented programming. Class A is too dependent on class B and could be badly affected by modifications to class B.

To avoid this strong dependency, we could use an abstraction of class B. We could use an interface, called IB, to replace class B as a property and then delegate the resolution of the interface IB with this concrete class to a tier component

ASP.NET Core 3.1 includes a very simple built-in DI container, which supports constructor injection. To make a service available for the container, you have to add it within the ConfigureService method of the Startup class. Without knowing it, you have already done that before for MVC.

Creating model

Step 1 : Add a new folder called Models to the project.

Step 2 : Add a new model by right-clicking on the Models folder in your project and selecting Add | Class, and name it ProductModel

public class ProductModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public double Price { get; set; }
}

Creating controller

Step 3 : Add a new controller and call it ProductController

Creating view

Step 4 : Right-click on the method called Index and choose Add View. Select the List template, choose ProductModel as the Model class, as mentioned in the previous point, and enable the usage of the layout page

Creating service

Step 5 : Add a new class called ProductService.cs to the Services folder.

using LearningAspNetCore.Models;

namespace LearningAspNetCore.Services
{
    public class ProductService
    {
        public List <ProductModel> GetSomeProducts()
        {
            return new List <ProductModel>() {
                new ProductModel() { Id = 1, Name = "iPhone", Price = 1234.5D },
                new ProductModel() { Id = 2, Name = "SamSung", Price = 901.8D },
            };
        }
    }
}

Step 6 : Right-click on the class and choose Quick Actions and Refactorings, and then click on Extract Interface…

Step 7 : Leave all of the default values in the pop-up window and click on OK.

Step 8 : Visual Studio 2019 will generate a new file called IProductService.cs, containing the extracted interface definition, as shown here:

public interface IProductService
{
    List<ProductModel> GetSomeProducts();
}

Step 9 : Update the ProductController created previously and apply the constructor injection mechanism:

using LearningAspNetCore.Services;

namespace LearningAspNetCore.Controllers
{
    public class ProductController : Controller
    {
        private readonly IProductService _service;

        public ProductController(IProductService service)
        {
            this._service = service;
        }
        public IActionResult Index()
        {
            var model = this._service.GetSomeProducts();
            return View(model);
        }
    }
}

Step 10 : Finally, we configure the ProductService life cycle in the ConfigureServices method:

using LearningAspNetCore.Services;
....
services.AddTransient<IProductService, ProductService>();
....

Step 11 : Test your application by pressing F5. We can see now the result in an HTML page: (/product)

Add Comment