【问题标题】:Unity IoC resolve and inject a collection of classes implementing a common interfaceUnity IoC 解析并注入实现公共接口的类集合
【发布时间】:2023-03-06 15:48:01
【问题描述】:

我有几个实现相同接口的类,以不同的名称注册。我想将它们作为一个集合注入到一个构造函数中,unity 不明白。

interface IA{}
interface IB { IEnumerable<IA> As { get; set; } }
class A1 : IA{}
class A2 : IA {}

class B : IB
{
    public IEnumerable<IA> As { get; set; }
    public B(IEnumerable<IA> ass)
    {
        As = ass;
    }

    public B(IA a)
    {
        var b = 1;
    }
}

现在我要注入它们

[TestMethod]
public void ResolveMultiple()
{
    var container = new UnityContainer();
    container.RegisterType<IA, A1>("A1");
    container.RegisterType<IA, A2>("A2");
    container.RegisterType<IB, B>();

    var b = container.Resolve<IB>();
    Assert.IsNotNull(b);
    Assert.IsNotNull(b.As);
    var manyAss = container.ResolveAll<IA>();
}

最后一行有效,所以我收集了两个类 (A1, A1) ,但没有创建 B 类。

是否需要额外的配置?

【问题讨论】:

    标签: c# dependency-injection inversion-of-control unity-container


    【解决方案1】:

    好的,解决方案是教 unity 使用 IEnumerable

    _container.RegisterType(typeof(IEnumerable<>), new InjectionFactory((unityContainer, type, name) => unityContainer.ResolveAll(type.GetGenericArguments().Single())));
    

    【讨论】:

    • 开箱即用,Unity 确实知道如何解析数组语法。因此,您可以将构造函数更改为 public B(IA[] ass)public B(params IA[] ass)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 2014-12-03
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多