本文介绍了如何确定服务是否已经添加到 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:24