本文介绍了如何确定服务是否已经添加到IServiceCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating helper classes to simplify configuration and injection of interfaces via IServiceCollection for a library. The libraries constructor contains a number of dependencies that are likely to have been injected earlier. If they aren't already inserted into IServiceCollection, the helper class should add them. How do I detect if the interface has already been injected?

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包括扩展方法,以防止添加服务(如果已存在).例如:

Microsoft has included extension methods to prevent services from being added if they already exist. For example:

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

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

To use them, you need to add this using directive:

using Microsoft.Extensions.DependencyInjection.Extensions;

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

If the built-in methods don't meet your needs, you can check whether or not a service exists by checking for its ServiceType.

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

这篇关于如何确定服务是否已经添加到IServiceCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 10:23