从.NET Standard 2.0库中读取app.config

时间:2017-09-28 10:33:37

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

我正在创建一个.NET Framework 2.0库,供.NET Framework 4.6.1应用程序使用 这个库需要EF Core,但我无法弄清楚如何阅读app.config。

在.NET Framework库中,我会像这样初始化我的DBContext:

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

但我不能这样做,因为在.NET Standard 2.0中找不到ConfigurationManager 如何从.NET Standard 2.0库中读取配置文件?

1 个答案:

答案 0 :(得分:6)

创建一个接口并对连接字符串使用依赖项反转,因此您的代码看起来像

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);
    }
}

然后,在.NET Framework中运行的消费应用程序可以创建自己的设置实现并在

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

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

所有时髦的孩子都可以使用环境变量:

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

赢得所有人