I have following snippet:
static void Main(string[] args) {
var container = new UnityContainer();
container.RegisterType<IConnection, SerialPortConnection>("SerialConnection");
container.RegisterType<IConnection, ParallelPortConnection>("ParallelConnection");
container.RegisterType<Device>("ParallelDevice");
container.RegisterType<Device>("SerialDevice");
}
I want to register type Device under two different names, so that depending on the name requested Device instance would be initialized with appropriate Connection. Following is one way to solve this, just for demonstration:
public class ParallelDevice : Device {
public ParallelDevice([Dependency("ParallelConnection")] IConnection connection) : base(connection) {}
}
public class SerialDevice : Device {
public SerialDevice([Dependency("ParallelConnection")] IConnection connection) : base(connection) {}
}
// and register with
container.RegisterType<Device, ParallelDevice>("ParallelDevice");
container.RegisterType<Device, SerialDevice>("SerialDevice");
Is there a better way to do this? Something like:
container.RegisterType<Device>("ParallelDevice").UseDependencyNames("ParallelConnection");
You can do it like this:
or like this:
This article has more examples as well as some extensions for Unity that allow you to write tests like this: