How to do it...

We've already talked about injecting dependencies with ASP.NET Core in Chapter 5, SOLID Principles, Inversion of Control, and Dependency Injection. We learned that the IoC mechanism is internal to ASP.NET Core. It's done by a constructor, and its life cycle has to be configured in the Configure method in Startup.cs. We'll make some adjustments, and everything will work automatically.

  1. First, let's see the repository to inject in the controller:
public interface IProductRepository{  int GetCountProducts();}public class ProductRepository : IProductRepository{  public int GetCountProducts()  {    return 10;  }}

As we can see, this repository has only one method that retrieves a list of strings.

  1. Next, let's inject this repository in ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.