使用 Unity 在同一个构造函数中实现多个接口

Multiple implementations of an interface in the same constructor with Unity

我的问题类似于 this question。然而,有一个重要的区别。我正在使用 Unity 容器。问题是我需要在同一个构造函数中使用一个接口的两个实例。这些实例可能来自相同的实现,也可能来自不同的实现。构造函数的简化版本如下。

public SomeService(IMyInterface instance1, IMyInterface instance2) : ISomeService

我之前提到的问题,在不同的classes中使用了不同的实现。但是在我的情况下,我需要在一个 class.

中进行分离

这在 Unity 中可行吗?如果没有,是否有最近的容器具有此功能?

您可以像这样使用命名注册和 InjectionConstructor

container.RegisterType<IMyInterface, Impl1>("Impl1");
container.RegisterType<IMyInterface, Impl2>("Impl2");
container.RegisterType<ISomeService, SomeService>(
    new InjectionConstructor(
        new ResolvedParameter<IMyInterface>("Impl1"),
        new ResolvedParameter<IMyInterface>("Impl2")));

var service = container.Resolve<ISomeService>();

IMO,最好不要使用 DI 容器,而是使用 Pure DI when you have "complex" object graphs like what you have here. See my article here 以获得更多详细信息。