Before reading this article, readers should have a basic understanding of Dependency Injection as well as .NET Core.

In general, when we create a 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 applications.

In simple terms, DI will do two actions

  1. Registering all the services with a given scope and maintains as Collection called a Container.
  2. Injecting the requested service by fetching from the Container.

This is not much complicated to include the Dependency Injection feature to the .NET Core Console applications. Just need to follow the below steps for better organized DI implementation in Command-Line applications.

Step-1: Need to add 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 services 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 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.

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();
sample1Service.DoSomething();

Step-5: The most important is to call the Dispose() method on the service provider object. As it will remove all the objects created if not, it will not disposed.

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<IService1Service>();
     sample1Service.DoSomething();
     
     if (serviceProvider is IDisposable)
     {
         ((IDisposable)serviceProvider).Dispose();
     }
}

 

Happy Coding 🙂