Search code examples
.net.net-core

How do you add a configuration file to a .NET Core console application?


When I create a .NET Core console application, an appsettings.json file is not included like it is with an ASP.NET Core application.


Solution

  • Typically, the configuration is injected into the constructor of a class. However, with console applications, dependency injection is not configured by default. So we need to add a few lines of code to accomplish this.

    1. First we need to add the Microsoft.Extensions.Hosting NuGet package.
    2. Add the appsettings.json file. NOTE: it must be named this exactly.
    3. Add the following code to the Main procedure of the Program.cs file:
    var host = Host.CreateDefaultBuilder()
        .ConfigureServices((context, services) => { 
            services.AddTransient<IDoSomethingService, DoSomethingService>(); 
        })
        .Build();
    
    var svc = ActivatorUtilities.CreateInstance<DoSomethingService>(host.Services);
    
    svc.Generate();
    
    1. You'll need the following using statements:
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    
    1. Create your class (and possibly interface) that will contain your application code. Make sure you inject the configuration into the constructor.
    class DoSomethingService : IDoSomethingService
    {
    
        private IConfiguration _config;
    
        public DoSomethingService(IConfiguration config)
        {
            _config = config;
        }
    
        public void Generate()
        {
            System.Console.WriteLine("Generate is running.");
            System.Console.WriteLine(_config.GetConnectionString("Test"));
        }
    
    }
    
    
    1. In this example, we are storing a connection string in the appsettings.json file like so:
    {
      "ConnectionStrings": {
        "Test": "TEST_CONNECTION_STRING"
      }
    }