Null result returned when getting section or connection string from Configuration

I had an error when using Dependency Injection in a Console App. I was trying to access the configuration to get a section or a connection string, and the result was always null.

The article relates only to the use of Host.CreateDefaultBuilder(). in a Console Application.

The Problem

I was using code similar to below but the connection string was not being set.

var builder = Host.CreateDefaultBuilder(args);

// add services
builder.ConfigureServices((hostingContext, services) =>
{
    services.AddLogging();
    services.AddTransient<PrototypeRunner>();
    services.AddDbContext<TestDBDataContext>(options =>
        options.UseSqlServer(hostingContext.Configuration.GetConnectionString("TestDB")));
});

The issue here was that the hostingContext was always null.

The Solution

To resolve it I built the configuration and used that to get the connection string, like so…

IConfiguration config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .Build();

// Using Default Builder
var builder = Host.CreateDefaultBuilder(args);

// add services
builder.ConfigureServices((hostingContext, services) =>
{
    services.AddLogging();
    services.AddTransient<PrototypeRunner>();
    services.AddDbContext<TestDBDataContext>(options =>
        options.UseSqlServer(config.GetConnectionString("TestDB"))); // for some reason hostingContext is null so use config
});

A Better Way

In my opinion, Host.CreateDefaultBuilder() is not the best method to use, I prefer to use Host.CreateApplicationBuilder(). See my article Dependency Injection in a Console App on how to do that.

Leave a Reply

Your email address will not be published. Required fields are marked *