Learn how to add and use Dependency Injection in your projects
- Install the
Microsoft.Extensions.Hosting
nuget package into your project. - In the
Program
class, create a static method calledCreateServiceCollection
. It will return anIServiceProvider
and 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
Program
class (below the using statements) and assign what it returns to a variable. - Back in
CreateServiceCollection
, in the empty space, addProductLogic
as a transient service using theAddTransient
method. 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
productLogic
varible with the following line:services.GetService<IProductLogic>
.services
is 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.