Reading app.config from .NET Standard 2.0 library

.net .net-standard-2.0 app-config c# entity-framework-core

Question

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?

1
5
10/12/2017 8:59:24 AM

Popular Answer

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

6
10/12/2017 9:24:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow