Unity:在运行时将注册类型替换为其他类型

geh*_*hho 30 dependency-injection unity-container

我们有一个场景,用户可以在运行时选择不同的硬件.在后台我们有几个不同的硬件类,它们都实现了一个IHardware接口.我们希望使用Unity为此接口注册当前选定的硬件实例.但是,当用户选择其他硬件时,这将要求我们在运行时替换此注册.

以下示例可能会更清楚:

public interface IHardware
{
    // some methods...
}

public class HardwareA : IHardware
{
    // ...
}

public class HardwareB : IHardware
{
    // ...
}


container.RegisterInstance<IHardware>(new HardwareA());

// user selects new hardware somewhere in the configuration...

// the following is invalid code, but can it be achieved another way?
container.ReplaceInstance<IHardware>(new HardwareB());
Run Code Online (Sandbox Code Playgroud)

这种行为能以某种方式实现吗?

顺便说一句:我完全清楚,从容器中解决的实例当然不会被新实例替换.我们会通过强迫他们再次解决实例来照顾自己.

小智 45

如果您不按名称区分它们,UnityContainer的RegisterInstance方法将始终覆盖最后一个注册条目.

所以,如果你打电话

container.RegisterInstance<IHardware>(new HardwareB());
Run Code Online (Sandbox Code Playgroud)

您将覆盖IHardware接口的注册,并在下次解析尝试时检索HardwareB