.NET Core 2控制台应用程序中的强类型配置设置

时间:2017-09-07 12:20:05

标签: c# configuration .net-core console-application .net-core-2.0

我想使用强类型类访问appsettings.json文件(可能还有其他配置文件)。 在.NET Core 1(例如https://weblog.west-wind.com/posts/2016/may/23/strongly-typed-configuration-settings-in-aspnet-core)中有很多关于这样做的信息,但是几乎没有关于.NET Core 2的信息。

此外,我正在构建一个控制台应用程序,而不是ASP.NET。

似乎配置API在.NET Core 2中已经完全改变了。我无法解决它。任何人?

编辑:我想也许Core 2文档还没有赶上。示例:https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationbinder?view=aspnetcore-2.0表示,您认为ConfigurationBinder存在于.NET Core 2中,但Microsoft.Extensions.Configuration和Microsoft.Extensions.Options的对象浏览器搜索没有显示任何内容。

我使用了NuGet控制台

  • 安装包Microsoft.Extensions.Options -Version 2.0.0
  • 安装包Microsoft.Extensions.Configuration -Version 2.0.0

1 个答案:

答案 0 :(得分:6)

感谢Martin Ullrich的观察,这导致了解决方案。这里有几件事情在发挥作用:

  • 我对DLL级别的引用很生疏,因为旧样式的“引用”(与.NET Core中的新“依赖”相反)隐藏了所有这些
  • 我假设安装NuGet Microsoft.Extensions.Configuration包会安装子命名空间DLL。事实上,NuGet Gallery中有很多软件包(参见here)。 NuGet控制台不会告诉您具体使用哪些DLL,但是一旦安装完毕,您就可以在解决方案浏览器中看到它们: enter image description here
    并且,在API Browser中搜索ConfigurationBinder什么也没有产生,我猜是因为它是扩展库的一部分。
  • Rick Strahl确实在帖子中提到了它(在问题中链接),但我仍然错过了它:例如,Bind方法看起来很像ConfigurationBinder上的静态方法。但实际上它是一种扩展方法。因此,在安装NuGet包时会神奇地出现。这使我们在很大程度上依赖于我尚未完成的文档。

总而言之,解决方案是:

  • 安装包Microsoft.Extensions.Configuration.Binder -Version 2.0.0
  • 安装包Microsoft.Extensions.Configuration.Json-Version 2.0.0

第一个提供.Bind方法,第二个提供.SetBasePath.AddJsonFile方法。

一旦我完善它,我会在一天左右添加最终代码。

编辑:

public class TargetPhoneSetting {
    public string Name { get; set; } = "";
    public string PhoneNumber { get; set; } = "";
}

public class AppSettings {
    public List<TargetPhoneSetting> TargetPhones { get; set; } = new List<TargetPhoneSetting>();
    public string SourcePhoneNum { get; set; } = "";
}

public static AppSettings GetConfig() {
    string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    var builder = new ConfigurationBuilder()
        .SetBasePath(System.IO.Directory.GetCurrentDirectory())
        .AddYamlFile("appsettings.yml", optional: false)
        ;
    IConfigurationRoot configuration = builder.Build();

    var settings = new AppSettings();
    configuration.Bind(settings);

    return settings;
}

请注意,上面的代码实际上是针对YAML配置文件的。您需要调整加载YAML以使用JSON的单行。我没有测试过这些,但它们应该很接近:

JSON:

{
  "SourcePhoneNum": "+61421999999",

  "TargetPhones": [
    {
      "Name": "John Doe",
      "PhoneNumber": "+61421999888"
    },
    {
      "Name": "Jane Doe",
      "PhoneNumber": "+61421999777"
    }
  ]
}

YAML:

SourcePhoneNum: +61421999999
TargetPhones:
    - Name: John Doe
      PhoneNumber: +61421999888
    - Name: Jane Doe
      PhoneNumber: +61421999777