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

时间:2018-03-19 23:26:37

标签: 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>();
}

1 个答案:

答案 0 :(得分:23)

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

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

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

using Microsoft.Extensions.DependencyInjection.Extensions;

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

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