将配置绑定到.NET Core 2.0中的对象图

Jos*_*lsh 9 c# .net-core-2.0

我正在制作.NET Core 2.0应用程序,我需要对其进行配置.我正在查看此文档,似乎在.NET Core 1.0中您可以这样做:

var appConfig = new AppSettings();
config.GetSection("App").Bind(appConfig);
Run Code Online (Sandbox Code Playgroud)

在.NET Core 1.1中,您可以:

var appConfig = config.GetSection("App").Get<AppSettings>();
Run Code Online (Sandbox Code Playgroud)

但在.NET Core 2.0中既不存在Bind也不存在.实现这一目标的新方法是什么?

谢谢,

玩笑

pok*_*oke 8

你仍然可以做这两件事.由于您处于控制台应用程序中,并且因此可能不使用ASP.NET Core元数据包,因此您需要确保具有正确的依赖项.

要将配置绑定到对象,您需要Microsoft.Extensions.Configuration.Binder包.然后,两种解决方案都应该正常工作.


顺便说一句.即使您在控制台应用程序中,您仍然可以使用ASP.NET Core附带的依赖注入容器.我个人发现设置起来非常简单,所以如果你仍然可以修改你的应用程序来使用它,那么它可能是值得的.设置将如下所示:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("config.json", optional: false)
    .Build();

var services = new ServiceCollection();
services.AddOptions();

// add your services here
services.AddTransient<MyService>();
services.AddTransient<Program>();

// configure options
services.Configure<AppSettings>(configuration.GetSection("App"));

// build service provider
var serviceProvider = services.BuildServiceProvider();

// retrieve main application instance and run the program
var program = serviceProvider.GetService<Program>();
program.Run();
Run Code Online (Sandbox Code Playgroud)

然后,所有注册的服务都可以像在ASP.NET Core中一样使用依赖项.然后,为了使用您的配置,您可以IOptions<AppSettings>像往常一样注入类型.


Jos*_*lsh 8

直到今天我终于想通了,我仍然对此有疑问。

该代码运行没有问题,但即使绑定后,所有属性仍为null。我正在这样做:

public class AppSettings
{
    public string MyProperty
}
Run Code Online (Sandbox Code Playgroud)

事实证明,您必须这样做:

public class AppSettings
{
    public string MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

仅当您的类具有“属性”而不是“字段”时,它才有效。我不清楚。