gpt4 book ai didi

c# - 如何确定服务是否已经添加到 IServiceCollection

转载 作者:可可西里 更新时间:2023-11-01 03:13:55 24 4
gpt4 key购买 nike

我正在创建辅助类以通过库的 IServiceCollection 简化接口(interface)的配置和注入(inject)。 libraries 构造函数包含许多可能早先注入(inject)的依赖项。如果它们尚未插入到 IServiceCollection 中,则帮助程序类应添加它们。如何检测接口(interface)是否已经注入(inject)?

public static void AddClassLibrary(this IServiceCollection services
, IConfiguration configuration)
{
//Constructor for ClassLibrary requires LibraryConfig and IClass2 to be in place
//TODO: check IServiceCollection to see if IClass2 is already in the collection.
//if not, add call helper class to add IClass2 to collection.
//How do I check to see if IClass2 is already in the collection?
services.ConfigurePOCO<LibraryConfig>(configuration.GetSection("ConfigSection"));
services.AddScoped<IClass1, ClassLibrary>();
}

最佳答案

Microsoft 已包含扩展方法以防止添加已存在的服务。例如:

// services.Count == 117
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118

要使用它们,您需要添加以下 using 指令:

using Microsoft.Extensions.DependencyInjection.Extensions;

NOTE: If that isn't visible, you may need to install the Microsoft.Extensions.DependencyInjection.Abstractions NuGet package.

如果内置方法不能满足您的需求,您可以通过检查其ServiceType来检查服务是否存在。

if (!services.Any(x => x.ServiceType == typeof(IClass1)))
{
// Service doesn't exist, do something
}

关于c# - 如何确定服务是否已经添加到 IServiceCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com