简体   繁体   English

是否有等效于 IServiceCollection 的“TryAdd”方法与 IOptions 一起使用<T>图案?

[英]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.

相关问题 即使使用 NuGet package 也无法使用 IServiceCollection - Can't use IServiceCollection even with NuGet package 使用 IServiceCollection.AddTransient、IServiceCollection.AddSingleton 和 IServiceCollectionAddScoped 方法的实际场景有哪些? - What are the practical scenarios to use IServiceCollection.AddTransient, IServiceCollection.AddSingleton and IServiceCollectionAddScoped Methods? 如何使用IOptions <T> 作为通用方法中的通用参数 - How to use IOptions<T> as a generic parameter in a generic method 将 IServiceCollection 扩展与 DryIoc 一起使用 - Use IServiceCollection extensions with DryIoc 在没有IOptions <T>的情况下从appsettings.json读取和使用设置? - Read and use settings from appsettings.json without IOptions<T>? 如何将选项模式 (IOptions) 与 Azure Functions Premium 一起使用? (它不允许在应用设置名称中使用冒号) - How can I use the Options pattern (IOptions) with Azure Functions Premium? (it does not allow colons in app setting names) 如何在 Azure Function V3 中使用 IOptions 模式,使用 .NET 核心 - How to use IOptions pattern in Azure Function V3 using .NET Core 什么是StructureMap的For Unity等效项 <T> ()。用(东西) - What's the Unity equivalent of StructureMap's For<T>().Use(SomeThing) 净核心IOptions <AppSettings> 采用 - Net Core IOptions<AppSettings> use 使用 IOptions 模式填充基类 - Populate base class using IOptions pattern
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM