将 IConfigurationSection 转换为 IOptions
Converting IConfigurationSection to IOptions
选项模式允许我创建包含配置值的选项对象,如下所述:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options
我需要 IDesignTimeDbContextFactory 实现中一个选项对象的值,以供 EF 在创建模型时使用。 (该配置部分中的值将用于数据播种,因此我将 IOptions 添加到数据库上下文构造函数中。)
因为我无法访问 IServiceCollection(因为它是设计时间 - 就像 运行 "dotnet ef migrations add" 时一样,我需要有另一种方法来转换 IConfigurationSection(代表我感兴趣的部分) 到我的自定义选项 class.
我可以知道如何在没有依赖注入的情况下做到这一点吗?
我猜你需要Bind方法:
var config = new ConfigurationBuilder()...Build();
var myOptions = new MyOptions();
config.GetSection("MyOptions").Bind(myOptions);
您可以使用 Bind(Configuration, object)
扩展方法来执行任何 object
的手动绑定。这是一个例子:
var myCustomOptions = new MyCustomOptions();
myConfigurationSection.Bind(myCustomOptions);
// Use myCustomOptions directly.
要将其包装在 IOptions<T>
中,请使用 Options.Create
:
IOptions<MyCustomOptions> myOptions = Options.Create(myCustomOptions);
ServiceCollectionContainerBuilderExtensions 使它在 SoapCore
中工作
我申请中的部分是这样计算的:
services.AddSingleton<IRESAdapterService>(new RESAdapterService(
new XController(
services.BuildServiceProvider().GetRequiredService<IOptions<XApiSettingsFromJsonClass>>(),
_xLogger
)));
也可用于完整性单元测试
你也可以使用
config.Get<MyCustomOptions>()
这是 Microsoft.Extensions.Configuration 命名空间的扩展方法。我在 Assembly Microsoft.Extensions.Configuration.Binder, Version=3.1.9.0 中看到了。也许,它也存在于早期版本中。那会给你设置对象本身。然后你可以将它包装到 IOptions 中,正如 Krik 在另一个答案中所展示的那样。
选项模式允许我创建包含配置值的选项对象,如下所述:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options
我需要 IDesignTimeDbContextFactory 实现中一个选项对象的值,以供 EF 在创建模型时使用。 (该配置部分中的值将用于数据播种,因此我将 IOptions 添加到数据库上下文构造函数中。)
因为我无法访问 IServiceCollection(因为它是设计时间 - 就像 运行 "dotnet ef migrations add" 时一样,我需要有另一种方法来转换 IConfigurationSection(代表我感兴趣的部分) 到我的自定义选项 class.
我可以知道如何在没有依赖注入的情况下做到这一点吗?
我猜你需要Bind方法:
var config = new ConfigurationBuilder()...Build();
var myOptions = new MyOptions();
config.GetSection("MyOptions").Bind(myOptions);
您可以使用 Bind(Configuration, object)
扩展方法来执行任何 object
的手动绑定。这是一个例子:
var myCustomOptions = new MyCustomOptions();
myConfigurationSection.Bind(myCustomOptions);
// Use myCustomOptions directly.
要将其包装在 IOptions<T>
中,请使用 Options.Create
:
IOptions<MyCustomOptions> myOptions = Options.Create(myCustomOptions);
ServiceCollectionContainerBuilderExtensions 使它在 SoapCore
中工作我申请中的部分是这样计算的:
services.AddSingleton<IRESAdapterService>(new RESAdapterService(
new XController(
services.BuildServiceProvider().GetRequiredService<IOptions<XApiSettingsFromJsonClass>>(),
_xLogger
)));
也可用于完整性单元测试
你也可以使用
config.Get<MyCustomOptions>()
这是 Microsoft.Extensions.Configuration 命名空间的扩展方法。我在 Assembly Microsoft.Extensions.Configuration.Binder, Version=3.1.9.0 中看到了。也许,它也存在于早期版本中。那会给你设置对象本身。然后你可以将它包装到 IOptions 中,正如 Krik 在另一个答案中所展示的那样。