我们有一个场景,用户可以在运行时选择不同的硬件。在后台,我们有几个实现了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());
有没有什么办法可以实现这种行为?
顺便说一下:我完全意识到已经从容器中解析出来的实例不会被新实例替换。当然,我们会通过强制重新解析实例来处理它们。