Unity:为单个构造函数参数指定实例并自动解析剩余参数类型?

Unity: Specify instance for single constructor parameter and auto-resolve remaining parameter types?

我有一个接口 INexus 在两个不同的 class 中使用。第一个 class Nexus 是核心功能,另一个是 "decorating class" NexusDecorator 接受 INexus 参数,调用它,并为结果。

public interface INexus
{
    string Eval();
}

public class Nexus : INexus
{
    public string Eval()
    {
        return "Hello World!";
    }
}

public class NexusDecorator : INexus
{
    private readonly INexus _nexus;
    private readonly IClock _clock;
    private readonly IPrettifyer _prettifyer;

    public NexusDecorator(INexus nexus, IClock clock, IPrettifyer prettifyer)
    {
        _nexus = nexus;
        _clock = clock;
        _prettifyer = prettifyer;
    }

    public string Eval()
    {
        var s = _clock.Now() + ": " + _nexus.Eval();
        return _prettifyer.Emphasize(s); // returns somehing like "<i>12:30: Hello World!</i>"
    }
}

我使用 Unity 来注册类型:

var container = new UnityContainer();

container.RegisterType<INexus, Nexus>("base")

container.RegisterType<INexus, NexusDecorator>(
    new InjectionConstructor(
        new ResolvedParameter<INexus>("base"),
        new ResolvedParameter<IClock>(),
        new ResolvedParameter<IPrettifyer>()
        ));

InjectionConstructor 设置了一个实例列表,这些实例使用注册的类型以正确的顺序匹配 NexusDecorator 的构造函数。这很好,但默认注册的唯一例外是使用以 Nexus class 为目标的命名 INexus 注册。必须指定 Unity 应该如何解决本质上是 IClockIPrettifyer.

的默认注册似乎过于繁琐

有没有办法告诉 Unity 覆盖构造函数的 INexus 参数并忽略其余参数的规范?

-西格德·加肖

正如@tsimbalar 指出的那样,这个问题之前已经被问过:

How do I use the Decorator Pattern with Unity without explicitly specifying every parameter in the InjectionConstructor

似乎简短的答案是:"You don't"。似乎 Unity 能够仅使用一个构造函数自动解析 类 的构造,但是一旦您开始指定单个参数,您就无法指定所有参数。

在链接的答案中,OP 承认,在他的情况下,使用 InjectionFactory 显式 new 对象图更具可读性,并使他能够在编译时赶上构造函数参数扩展。

缺点似乎是您可能需要维护一个大型对象图,但实际上:使用 new 创建的每个对象都可以 解析 如果需要,请插入。