首页 > 解决方案 > .NET Core 依赖注入 - 解析接口的实现和 IEnumerable

问题描述

我有IMyType几个实现的接口SomeMyTypeOtherMyType.

我想同时使用具体类型,以及实现IMyType接口的所有类型的 IEnumerable。

这些可能是服务中的声明。

private readonly IEnumerable<IMyType> instances;
private readonly SomeMyType someType;
private readonly OtherMyType otherType;

完成这项工作的一种方法是使用以下扩展:

public static IServiceCollection AddMyType<T>(this IServiceCollection serviceCollection)
    where T : class, IMyType =>
    serviceCollection
        .AddSingleton(typeof(IMyType), typeof(T))
        .AddSingleton(typeof(T));

这为具体类型和接口添加了一个单例。

这是配置依赖项的好方法吗?

还有其他改进解决方案的方法吗?我在想这是否会创建两个 T 实例,或者框架是否试图用第一个 T 解析第二个单例。

标签: c#.net-coredependency-injection

解决方案


注册类,注册接口时,使用委托工厂获取注册类。

public static IServiceCollection AddMyType<T>(this IServiceCollection serviceCollection)
    where T : class, IMyType =>
    serviceCollection
        .AddSingleton<T>();
        .AddSingleton<IMyType>(sp => sp.GetService<T>());

哪个会像

services.AddMyType<SomeMyType>();
services.AddMyType<OtherMyType>();

为了在这种情况下解决您的服务,为了获得所有已注册的IMyType,注入IEnumerable<IMyType>

private readonly IEnumerable<IMyType> instances;

public MyClass(IEnumerable<IMyType> instances) {
    this.instances = instances;

    //...
}

已经注册的具体类型也可以根据需要显式注入

private readonly SomeMyType someType;

public MyClass(SomeMyType someType) {
    this.someType = someType;

    //...
}

推荐阅读