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

Ben*_*yre 3 c# configuration console-application .net-core .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

Ben*_*yre 6

感谢Martin Ullrich的观察,这导致了解决方案.这里有几件事情在玩:

  • 我对DLL级别的引用很生疏,因为旧样式的"引用"(与.NET Core中的新"依赖"相反)隐藏了所有这些
  • 我假设安装NuGet Microsoft.Extensions.Configuration包将安装子命名空间DLL.事实上,NuGet Gallery中有很多软件包(见这里).NuGet控制台不会告诉您具体使用哪些DLL,但是一旦安装完毕,您就可以在解决方案浏览器中看到它们: 在此输入图像描述
    并且,在API浏览器中搜索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;
}
Run Code Online (Sandbox Code Playgroud)

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

JSON:

{
  "SourcePhoneNum": "+61421999999",

  "TargetPhones": [
    {
      "Name": "John Doe",
      "PhoneNumber": "+61421999888"
    },
    {
      "Name": "Jane Doe",
      "PhoneNumber": "+61421999777"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

YAML:

SourcePhoneNum: +61421999999
TargetPhones:
    - Name: John Doe
      PhoneNumber: +61421999888
    - Name: Jane Doe
      PhoneNumber: +61421999777
Run Code Online (Sandbox Code Playgroud)