NET泛型接口的依赖注入和GetServices查询

时间:2019-02-28 20:27:21

标签: c# asp.net asp.net-core asp.net-core-2.0

在寻求一些建议后,我陷入了与仿制药的纠缠中。说我有以下界面:

public interface IThing<T>
{
  string DoStuff(T input);
}

和以下实现:

public class GenericThing<T> : IThing<T> where T : Person
{
    public string DoStuff(T input)
    {
        return typeof(T).Name;
    }
}

public class GenericThing2<T> : IThing<T> where T : Animal
{
    public string DoStuff(T input)
    {
        return typeof(T).Name;
    }
}

注册如下:

services.AddSingleton(typeof(IThing<>), typeof(GenericThing<>));
services.AddSingleton(typeof(IThing<>), typeof(GenericThing2<>));

是否有一种方法可以识别服务集合中实现IThing <>的所有对象?

1 个答案:

答案 0 :(得分:0)

您可以遍历ServiceCollection中的服务描述符,并检查类型以查看哪些是通用的以及什么是通用类型参数。

通常,我建议在服务提供者中注册具体类型,而不是抽象类型,因为创建没有具体类型的服务会很困难!例如,

services.AddSingleton( typeof(IThing<Person>, GenericThing<Person>)

在您要注册两次相同的接口的情况下,您可能还希望为服务提供名称字符串,因为否则,当您尝试获取服务时,无法区分多个服务。但是通常情况下,人们试图避免两次注册相同的接口。

sjb