Connection Strings in different .NET versions config

50 Views Asked by At

I'm building a Windows Service in .NET 8 to monitor resources. This service references an old .NET Framework 4.6.1 project. I do not have the time or resources to rewrite the functionality in .NET 8.

The problem is the old project attempts to retrieve connection strings via the ConfigurationManager. Because we are using appsettings.json in the .NET 8 project, the old project triggers a null pointer exception.

Short of dependency injection or passing the connection as a parameter, is it possible to solve the config null pointer issue in a simple way?

1

There are 1 best solutions below

0
Panagiotis Kanavos On

The easiest option is to modify the .NET Framework code to use Microsoft.Extensions.Configuration. The package targets .NET Standard 2.0 and .NET Framework 4.6.2 among others. So does Microsoft.Extensions.Hosting. One could easily add a generic host with preconfigured DI, Configuration, logging etc and read connection strings with :

using IHost host = Host.CreateApplicationBuilder(args).Build();
var configuration=host.Services.GetRequiredService<IConfiguration>();

var connectionString=configuration.GetConnectionString("MyDB");

or, if we're very, very lazy :

var builder=Host.CreateApplicationBuilder(args);
var connectionString=builder.Configuration.GetConnectionString("MyDB");

or use just the Configuration middleware:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

The .NET Framework configuration system makes it hard to even use custom XML sections, much less JSON files. Even adding a custom XML section requires creating a new assembly that's referenced in app.config.

By the way, 4.6.1 went out of support 2 years ago. By that time, all supported Windows versions already run 4.6.2 at least. Right now the oldest supported runtime is 4.6.2.