08 – .NET Core Console Application – DI Custom Classes
Configuration and Logger can be injected by default without any additional code. But if you have inject objects you created you have to configure those separately.
To demonstrate this, let’s create a new folder called Repositories. In this folder, we’ll create a new class called SampleRepository.
We’ll use the constructor to inject Configuration and Logger. We already know those are configured for Dependency Injection out of the box.
Let’s also create a method called DoSomething where we’ll perform some logging and get the Connection String from the Configuration. Finally we’ll log the connection string just to show that we can access anything the Worker.cs file can access just the same.
Let’s make sure that the class is public, we’ll create the interface from it and clean up the using statements.
Next, we’ll go into the Program.cs file to configure Dependency Injection for the Sample Repository class we just created.
We’ll do so by adding a call to ConfigureServices which will receive a function that takes 2 parameters:
• Context
• Services
We’ll use a fat-arrow function to fill in the body of the method. In there we’ll call Services AddScoped which is a Generic method where you supply the mapping from the interface to the concrete class.
Finally, we’ll inject that into the Worker class and call it from the Run method.
Let’s run it and see what we get… Holy Cow!!! Works like a charm I must say.
In the next video we’ll talk about Environment Variable… See you there!