如何确定服务是否已添加到IServiceCollection中

Dan*_*ney 15 c# dependency-injection .net-core

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

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>();
}
Run Code Online (Sandbox Code Playgroud)

Nig*_*888 38

Microsoft已包含扩展方法,以防止添加服务(如果已存在).例如:

// services.Count == 117
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118
services.TryAddScoped<IClass1, ClassLibrary>();
// services.Count == 118
Run Code Online (Sandbox Code Playgroud)

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

using Microsoft.Extensions.DependencyInjection.Extensions;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 请注意,如果您想要调用单独库中提到的扩展方法,并且您正在挑选 Microsoft 包,那么可以在 Microsoft.Extensions.DependencyInjection.Abstractions nuget 包中找到它们。 (2认同)