Home Is there a universal config file for .Net Standard 2.0 Class Library?
Reply: 2

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

Brad Bamford
Brad Bamford Published in 2017-11-14 19:05:43Z

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.

CodeFuller Reply to 2017-11-14 19:34:13Z

.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. Đ•here 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();
var configuration = configurationBuilder.Build();

//  IServiceCollection services


//  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.

Brad Bamford
Brad Bamford Reply to 2017-11-15 00:17:37Z

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
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314045 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO