Before reading this article, readers should have a basic understanding of Dependency Injection as well as .NET Core.
In general, when we create new .NET core web applications, the template will include the Dependency Injection logic in a structured way. But this is not prepared when we create a new .NET Core-based console/command-line application.
In simple terms, DI will do two actions.
- Register all the services with a given scope and maintain a Collection called a Container.
- Inject the requested service by fetching from the Container.
There is not much-complicated coding involved in order to include the Dependency Injection feature in the .NET Core Console applications. You just need to follow the below steps for better organized DI implementation in Command-Line applications.
Step 1. Add the following NuGet package before writing any logic here.
Microsoft.Extensions.DependencyInjection
Step 2. As mentioned above in point #1, we need to create a collection/container to hold the service information as follows.
var collection = new ServiceCollection();
collection.AddScoped<ISample1Service, Sample1Service>();
collection.AddScoped<ISample2Service, Sample2Service>();
Here ServiceCollection class helps us in providing scope to register our services with a defined scope (Scoped/Transient/Singleton).
Step 3. Once we have a collection of Services, we need to have a provider to fetch the requested service from the container whenever needed. To do so, we need to create a ServiceProvider from the ServiceCollection object as follows.
var serviceProvider = collection.BuildServiceProvider();
Step 4. As the service provider is ready, we can call the service based on their interface as follows.
var sample1Service = serviceProvider.GetService<ISample1Service>();
sample1Service.DoSomething();
Step 5. The most important step is to call the Dispose() method on the service provider object, as it will remove all the objects created; if not, it will not do that.
serviceProvider.Dispose();
Following is the complete code.
static void Main(string[] args)
{
var collection = new ServiceCollection();
collection.AddScoped<ISample1Service, Sample1Service>();
// ...
// Add other services
// ...
IServiceProvider serviceProvider = collection.BuildServiceProvider();
var sample1Service = serviceProvider.GetService<ISample1Service>();
sample1Service.DoSomething();
if (serviceProvider is IDisposable)
{
((IDisposable)serviceProvider).Dispose();
}
}
Happy Coding!