Injecting dependencies and configuring IoC for a controller
In this recipe, you will learn how to inject a dependency with a constructor in a controller, and how to configure its lifetime.
Getting ready
We created an empty web application with VS 2017, and then added an empty controller to it. Let's create a repository with hardcoded values to be injected into the controller.
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.
- First, let's see the repository to inject in the controller:
public interface IProductRepository { int GetCountProducts(); } public class ProductRepository : IProductRepository { public int GetCountProducts() { return...