我正在尝试绑定一些可配置的设置。这些值是通过 app-settings.local.json 提供的。要绑定的模型称为可配置设置。我尝试遵循一些教程并解决问题:
- https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/
- https://github.com/aspnet/Configuration/issues/411
- 无法从 .NET Core 项目中的 JSON appsettings 文件设置配置
- 即使 GetSection 正在工作,ServiceCollection 也会为 IOptions 返回 null
我试图遵循此处给出的建议并将其应用到我自己的应用程序中。经过 4 小时的尝试,我无法让它工作。要么我缺乏实现这一点所需的基本知识,要么我忽略了一些东西。
我的 ConfigurableSettings 类的结构如下:
public class ConfigurableSettings
{
public AppSettings _AppSettings;
public DgeSettings _DgeSettings;
public class AppSettings
{
[JsonProperty("SoftDelete")]
public bool SoftDelete { get; set; }
}
public class DgeSettings
{
[JsonProperty("zipFileUrl")]
public string zipFileUrl { get; set; }
[JsonProperty("sourceFileUrl")]
public string sourceFileUrl { get; set; }
}
}
我的 ConfigureServices 结构如下:
public static void ConfigureServices(IServiceCollection serviceCollection, string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("app-settings.local.json", true)
.AddJsonFile("app-settings.json", false)
.Build();
serviceCollection.Configure<ConfigurableSettings>(options => configuration.GetSection("AppSettings").Bind(options));
serviceCollection.Configure<ConfigurableSettings>(options => configuration.GetSection("DgeSettings").Bind(options));
var services = serviceCollection.BuildServiceProvider();
var options = services.GetService<IOptions<ConfigurableSettings>>();
serviceCollection.AddLogging(loggingBuilder =>
{
loggingBuilder.AddConfiguration(configuration.GetSection("Logging"));
loggingBuilder.AddConsole();
loggingBuilder.AddDebug();
});
serviceCollection.AddServices(configuration);
serviceCollection.AddNopCommerceServices(configuration);
serviceCollection.AddTransient<Comparator>();
serviceCollection.AddTransient<UpdateManager>();
serviceCollection.AddTransient<DgeRequestAuthenticator>();
serviceCollection.AddTransient<ISourceConnector, DgeConnector>();
serviceCollection.AddTransient<IDestinationConnector, NopCommerceConnector>();
}
我的 app-settings.local.json 配置如下:
{
"AppSettings": {
"SoftDelete": true
},
"DgeSettings": {
"zipFileUrl" : "www.example-url.com",
"sourceFileUrl" : "www.example-url.com"
}
}
当我尝试在类中使用它时,我在构造函数中调用它,如下所示:
private readonly ConfigurableSettings _settings;
public AlphaBetaService(IOptions<ConfigurableSettings> settings)
{
_settings = settings.Value;
}
有人可以帮我找出我做错了什么吗?