Unity: Replace registered type with another type at runtime
- by gehho
We have a scenario where the user can choose between different hardware at runtime. In the background we have several different hardware classes which all implement an IHardware interface. We would like to use Unity to register the currently selected hardware instance for this interface. However, when the user selects another hardware, this would require us to replace this registration at runtime.
The following example might make this clearer:
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());
Can this behavior be achieved somehow?
BTW: I am completely aware that instances which have already been resolved from the container will not be replaced with the new instances, of course. We would take care of that ourselves by forcing them to resolve the instance once again.