Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: Replace registered type with another type at runtime

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.

like image 808
gehho Avatar asked Apr 23 '10 09:04

gehho


1 Answers

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

like image 92
Gerald Keider Avatar answered Nov 11 '22 08:11

Gerald Keider