【问题标题】:How to determine if service has already been added to IServiceCollection如何确定服务是否已添加到 IServiceCollection
【发布时间】:2018-08-28 15:56:58
【问题描述】:

我正在创建帮助类以通过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>();
}

【问题讨论】:

  • services 有哪些方法和属性可用?您需要使用智能感知进行检查。在 msdn 上关注 IServiceCollection 的文档

标签: c# dependency-injection .net-core


【解决方案1】:

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

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

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

using Microsoft.Extensions.DependencyInjection.Extensions;

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

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

【讨论】:

  • 请注意,如果您想调用单独库中提到的扩展方法并且您正在挑选 Microsoft 包,那么可以在 Microsoft.Extensions.DependencyInjection.Abstractions nuget 中找到它们包。
猜你喜欢
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多