Is there a universal config file for .Net Standard 2.0 Class Library?

Viewed 22454

I have a Class Library that I'm converting to a .Net Standard 2 class library in order to also use in ASP.Net Core 2.0 projects.

The library has always read from a config file items such as SMTP settings, connection strings etc.

In Web Projects it finds these values in web.config.

In Console/WinForms it finds these values in app.config.

Is there an equivalent config file for .Net Core 2.0 projects that "just works" like the previous examples?

I assume the answer is no, but looking for best way to handle this given the library is used across the organization, so maintaining backwards compatibility is important.

2 Answers

Turns out System.Configuration.ConfigurationManager was added back in .NETStandard 2.0.

Just pull it in from nuget and compile the .NETStandard 2.0 class library project.

Then, the library will work across projects using standard config files:

  • Net Core 2.0 projects use app.config
  • Web projects work from web.config
  • Console and Windows apps work with app.config

.Net Core revised configuration approach greatly.

You don't call ConfigurationManager.AppSettings["someSetting"] anymore whenever you need value for some setting. Instead you load configuration on application startup with ConfigurationBuilder. There could be multiple configuration sources (json or/and xml configuration file, environment variables, command line, Azure Key Vault, ...).

Then you build your configuration and pass strongly typed setting objects wrapped into IOption<T> to consuming classes.

Here is a basic idea of how it works:

//  Application boostrapping

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

//  IServiceCollection services

services.AddOptions();
services.Configure<SomeSettings>(configuration.GetSection("SomeSection"));

//  Strongly typed settings

public class SomeSettings
{
    public string SomeHost { get; set; }

    public int SomePort { get; set; }
}

//  Settings consumer

public class SomeClient : ISomeClient
{
    public SomeClient(IOptions<SomeSettings> someSettings)
    {
        var host = someSettings.Value.SomeHost;
        var port = someSettings.Value.SomePort;
    }
}

//  AppSettings.json

{
  "SomeSection": {
    "SomeHost": "localhost",
    "SomePort": 25
  }
}

For more details check article Configure an ASP.NET Core App.

I'm afraid that it will be difficult (trying to avoid word 'impossible') to maintain backward compatibility.

Related