views:

120

answers:

2

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.

+1  A: 

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

Gerald Keider
That's cool, did not know/try that. Thanks a lot!
gehho
A: 

Other readers interested in this question, should also read this pretty detailed answer by ctavares in the Unity Codeplex forum.

gehho