Skip to content

Setup dependency Injection in .Net Core Console App

Dependency Injection is widely used design pattern and in case of asp.net core, it comes already configured with project templates. But we also have our ancient console template, which is new but everything in it is pretty much at the very basic and no DI support out of box. There you have to manually add it.

In this blog post, I will show you how you can add dependency injection in .Net Core console application. This can be applied to any .Net core version, .Net core 1.0 to .Net 6.

We need to install these packages first from NuGet:

Microsoft.Extensions.DependencyInjection

Now we will create an instance of ServiceCollection class. We will use this instance to register all the services, map the interfaces with their implementation classes and later we can use this instance to get all these services and it will automatically inject the dependency.

After this, At the very minimum your console application’s program.cs file will look like this:

using DemoBL;
using Microsoft.Extensions.DependencyInjection;

namespace MyConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {

            var serviceProvider = new ServiceCollection()
                // Add your services here..
                .AddSingleton<IDemoService, DemoService>()
                .BuildServiceProvider();

            // Now get Your Services like this
            var demoService = serviceProvider.GetRequiredService<IDemoService>();

            demoService.SayHello();
        }
    }
}

Here IDemoService and DemoService comes from another class library DemoBL, which I created just to represent real-life third party library on which your application can depend.

I showed only the usage of another class library, but DI can be used to fetch many other services, for example getting configuration values from appsettings.json file.

Get Configuration File values from appsettings.json file in .Net Core Console App

To read configuration files from appsettings.json file we will need below package from nuget:

Microsoft.Extensions.Configuration.Json

Now we need to read appsettings.json file using ConfigurationBuilder. Add a new file named appsettings.json file in your console app project. Make sure you set this file to copy always. You can do this by right click on this file, select properties. Then set “Copy to Output Directory” to “Copy Always“. Lets add some configuration value in it.

{
  "ConnectionStrings": {
    "default": "your-connectioin-string"
  },
  "secret_key": "this-is-secret-key"
}

After that we can use the IConfiguration type variable to access the configuration. Below are the changes if we add configuration in our previous code snippet:

using DemoBL;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp2DITest
{
    internal class Program
    {
        private static IConfiguration configuration;
        static void Main(string[] args)
        {
            configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build(); // Make sure appsettings.json is set to include in bin directory. Set it as Copy always.

            var serviceProvider = new ServiceCollection()
                // Add your services here..
                .AddSingleton<IDemoService, DemoService>()
                .AddSingleton<IConfiguration>(Program.configuration)
                .BuildServiceProvider();

            // Now get Your Services like this
            var demoService = serviceProvider.GetRequiredService<IDemoService>();
            var config = serviceProvider.GetRequiredService<IConfiguration>();

            demoService.SayHello();

            // Now we can get configuration directly as long as we are in Program class
            Console.WriteLine($"Deault Connection String is: {configuration.GetConnectionString("Default")}");
            Console.WriteLine($"Secret key value is: {configuration.GetSection("secret_key").Value}");

            // For classes other than Program, we need to access it from service reference like this:
            Console.WriteLine($"Secret key value is: {config.GetSection("secret_key").Value}");
        }
    }
}

Now if run this code, we will get below result:

Hello from Demo Service.
Deault Connection String is: your-connectioin-string
Secret key value is: this-is-secret-key
Secret key value is: this-is-secret-key

Here we can directly use the configuration variable as long as we are in Program class, For other classes we will need to get the IConfiguration service, of course you will need to get the reference of service provider from service scope.

Here is a helpful video which shows these concepts:

If you have any questions, feel free to ask in comments section below.

Be First to Comment

Leave a Reply

Your email address will not be published.