Unity: Replace registered type with another type at runtime
Posted
by gehho
on Stack Overflow
See other posts from Stack Overflow
or by gehho
Published on 2010-04-23T09:59:20Z
Indexed on
2010/04/23
10:03 UTC
Read the original article
Hit count: 249
unity
|dependency-injection
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.
© Stack Overflow or respective owner