Learn how to add and use Dependency Injection in your projects
- Install the
Microsoft.Extensions.Hostingnuget package into your project. - In the
Programclass, create a static method calledCreateServiceCollection. It will return anIServiceProviderand take no arguments. - In this method, return the following code:
That empty line is where you will configure all of your services.
new ServiceCollection() .BuildServiceProvider(); - Call this new method at the top of the
Programclass (below the using statements) and assign what it returns to a variable. - Back in
CreateServiceCollection, in the empty space, addProductLogicas a transient service using theAddTransientmethod. This method is an extension method, so you will need to add a using statement for it. This method is a generic method that takes 2 type parameters, the first will be the interface and the second will be the concrete class. - At the top of the program class, replace the assignment of the
productLogicvarible with the following line:services.GetService<IProductLogic>.servicesis the name of the variable you made in step 4, so it might be different name for you. - Run the program to ensure that you made the changes correctly.