Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading app.config from .NET Standard 2.0 library

I'm creating a .NET Standard 2.0 library to be consumed from a .NET Framework 4.6.1 application.
This library needs EF Core, but I can't figure out how to read the app.config.

In a .NET Framework library I would initialize my DBContext like this:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
}

But I can't do it since ConfigurationManager is nowhere to be found in .NET Standard 2.0.
How can I read the configuration file from a .NET Standard 2.0 library?

like image 236
BgrWorker Avatar asked Sep 28 '17 10:09

BgrWorker


People also ask

Can class library have app config?

No, class libraries can hold setting files, but their values will be defined in the application configuration (web. config, app.

How read app config file in C# Windows application?

Add the App. config file to your project. After creating a . NET Framework project, right-click on your project in Solution Explorer and choose Add > New Item. Choose the Application Configuration File item and then select Add.


1 Answers

Create an interface and use dependency inversion for the connection string, so your code will look something like

public interface IConnectionSettings
{
    string MyDatabaseConnectionString { get; }
}

class MyClass
{
    private readonly IConnectionSettings _connectionSettings;

    public MyClass(IConnectionSettings connectionSettings)
    {
        _connectionSettings = connectionSettings;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_connectionSettings.MyDatabaseConnectionString);
    }
}

Then the consuming app running in .NET Framework can then create their own settings implementation and pass it in

public class ConfigurationManagerConnectionSettings : IConnectionSettings
{
    public string MyDatabaseConnectionString { get; }
        = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
}

var s = new ConfigurationManagerConnectionSettings();
var myClass = new MyClass(s);

And all the hipster kids can use environment variables:

public class EnvironmentVariableConnectionSettings : IConnectionSettings
{
    public string MyDatabaseConnectionString { get; }
        = Environment.GetEnvironmentVariable("MyDatabaseConnectionString");
}

Win for everyone

like image 147
Kevin Smith Avatar answered Oct 12 '22 23:10

Kevin Smith