【问题标题】:Dependency Injection and Querying GetServices with Generic Interfaces .Net Core依赖注入和使用通用接口查询 GetServices .Net Core
【发布时间】:2019-07-22 20:12:50
【问题描述】:

在得到一些建议后,我与泛型陷入了困境。假设我有以下界面:

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 的所有对象?

【问题讨论】:

  • 你想完成什么?是否需要在控制器中获取所有已注册的IThing&lt;&gt; 实例?

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


【解决方案1】:

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

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

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

如果您想注册两次相同的接口,您可能还需要为服务提供名称字符串,因为否则当您尝试获取服务时无法区分多个服务。但是,通常会尽量避免两次注册同一个接口。

sjb

【讨论】:

  • 我想我的目标最终是将 IThing 的集合传递给控制器​​。也许我以错误的方式构建它,但如果您想象控制器想要调用 IThing 类型的多个服务。我试图绕过向构造函数添加许多 IThings。
  • 是的。您需要 (a) 在 IThing 接口上指定不同的变体(例如一系列派生接口)并从服务提供商处获取这些变体;或 (b) 在您注册不同的 GenericThing 变体时指定不同的名称;或者(c)注册一个 IList> 而不是注册多个 IThing 的
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 2015-09-11
相关资源
最近更新 更多