Unity: Replace registered type with another type at runtime

gehho picture gehho · Apr 23, 2010 · Viewed 12.7k times · Source

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.

Answer

Gerald Keider picture Gerald Keider · Apr 23, 2010

The method RegisterInstance of the UnityContainer will always override the last registration entry if you do not distinguish them by name.

So if you call

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

you will override the registration for the interface IHardware and will retreive HardwareB on the next resolving attempt