[英]Is there an equivalent to IServiceCollection's "TryAdd" methods for use with the IOptions<T> pattern?
I find the .NET Core IOptions pattern, as expressed in the syntax below, to be quite helpful.我发现 .NET Core IOptions 模式(如下面的语法所示)非常有帮助。
services.Configure<MySettings>(configuration.GetSection("MySettings"));
I also find the TryAdd methods helpful for guarding against duplicating a service registration, like this:我还发现 TryAdd 方法有助于防止重复服务注册,如下所示:
services.TryAddTransient<IMyService, MyService>();
I'm wondering if anyone knows of any technique for accomplishing the same thing with IOptions, or if duplicate registration protection is, perhaps, built into the framework.我想知道是否有人知道使用 IOptions 完成相同事情的任何技术,或者重复注册保护是否内置于框架中。 In other words, I'm looking for something like this:
换句话说,我正在寻找这样的东西:
services.TryConfigure<MySettings>(configuration.GetSection("MySettings"));
Actually, I had the same "issue".实际上,我有同样的“问题”。 I resolved in this way:
我是这样解决的:
if (!services.Any(d => d.ServiceType == typeof(IConfigureOptions<MySettings>)))
{
services.Configure<MySettings>(configSection);
}
This solution was based on Microsoft TryAdd code .此解决方案基于Microsoft TryAdd 代码。
Tip: You can create an extension method for it.提示:您可以为其创建扩展方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.