Implementing Dependency Injection In .NET Core Console Applications

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 related 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,
  1. Register all the services with a given scope and maintain a Collection called a Container.
  2. 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,
  1. Microsoft.Extensions.DependencyInjection     
Step 2
As mentioned above in point #1, we need to create a collection/container to hold the services information as follows,
  1. var collection = new ServiceCollection();    
  2. collection.AddScoped<ISample1Service, Sample1Service>();    
  3. collection.AddScoped<ISample2Service, Sample2Service>();    
Here ServiceCollection class helps us in providing scope to register our services with define 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.
  1. var serviceProvider = collection.BuildServiceProvider();     
Step 4
As the service provider is ready, we can call the service based on their interface as follows.
  1. var sample1Service = serviceProvider.GetService();    
  2. 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.
  1. serviceProvider.Dispose();     
Following is the complete code,
  1. static void Main(string[] args) {  
  2.     var collection = new ServiceCollection();  
  3.     collection.AddScoped < ISample1Service, Sample1Service > ();  
  4.     // ...    
  5.     // Add other services    
  6.     // ...    
  7.     IServiceProvider serviceProvider = collection.BuildServiceProvider();  
  8.     var sample1Service = serviceProvider.GetService < IService1Service > ();  
  9.     sample1Service.DoSomething();  
  10.     if (serviceProvider is IDisposable) {  
  11.         ((IDisposable) serviceProvider).Dispose();  
  12.     }  
  13. }  
Happy Coding :)

Similar Articles