Bru*_*ell 5 c# dependency-injection .net-core asp.net-core
我编写了一个扩展方法,IServiceCollection其中包含一个选项委托.我的问题是我必须首先验证配置的选项(例如过滤掉null值),因为继续并实例化依赖于这些选项的服务是不安全的.
public static class ServiceCollectionExtensions {
public static void AddServices(
this IServiceCollection services,
Action<ServiceOptions> configureOptions)
{
// Configure service
services.AddSingleton<IAbstraction, Implementation>();
// Validate options here...
// Configure options
services.Configure(configureOptions);
}
}
Run Code Online (Sandbox Code Playgroud)
如何在此验证在不调用委托的情况下正确指定了选项configureOptions?我不想依赖默认值,ServiceOptions因为我想强制设置一些设置.
从此以后OptionsBuilder,IOptions<T>.Value是一个很好的选择.此函数也采用配置委托,但最后执行,因此所有内容都已配置.
public static class ServiceCollectionExtensions {
public static void AddServices(
this IServiceCollection services,
Action<ServiceOptions> configureOptions)
{
// Configure service
services.AddSingleton<IAbstraction, Implementation>();
// Configure and validate options
services.AddOptions<ServiceOptions>()
.Configure(configureOptions)
.Validate(options => {
// Take the fully configured options and return validity...
return options.Option1 != null;
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1162 次 |
| 最近记录: |