Unity:在配置期间指定依赖关系名称

时间:2009-12-28 21:36:00

标签: configuration dependency-injection unity-container

我有以下代码段:

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");
}

我想在两个不同的名称下注册类型Device,以便根据请求的名称Device实例进行初始化,并使用适当的Connection。以下是解决此问题的一种方法,仅用于演示:

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");

有更好的方法吗?类似的东西:

container.RegisterType<Device>("ParallelDevice").UseDependencyNames("ParallelConnection");

2 个答案:

答案 0 :(得分:4)

您应该努力使代码不受DI Container特定的影响。在这种情况下,您可以简单地定义设备而无需引用Unity。这里以SerialDevice为例,但ParallelDevice类完全相似:

public class SerialDevice : Device
{
    public SerialDevice(IConnection connection)
        : base(connection) { }
}

您可以像这样配置容器:

container.RegisterType<IConnection, SerialPortConnection>("SerialConnection");
container.RegisterType<IConnection, ParallelPortConnection>("ParallelConnection");
container.RegisterType<Device, SerialDevice>("SerialDevice",
    new InjectionConstructor(new ResolvedParameter<IConnection>("SerialConnection")));
container.RegisterType<Device, ParallelDevice>("ParallelDevice",
    new InjectionConstructor(new ResolvedParameter<IConnection>("ParallelConnection")));

这将允许您解决这两个Device对象:

var serialDevice = container.Resolve<Device>("SerialDevice");
var parallelDevice = container.Resolve<Device>("ParallelDevice");

答案 1 :(得分:2)

你可以这样做:

var container = new UnityContainer()
    .RegisterType<IConnection, SerialConnection>("SerialConnection")
    .RegisterType<Device, SerialDevice>(new InjectionConstructor(
        new ResolvedParameter<IConnection>("SerialConnection")));

或者像这样:

container
    .Configure<InjectedMembers>()
    .ConfigureInjectionFor<ParallelDevice>(new InjectionConstructor(
        new ResolvedParameter<IConnection>("ParallelConnection")));

This article有更多示例以及Unity的一些扩展,允许您编写如下测试:

[Test]
public void Should_inject_named_instance_of_encryption_provider()
{
    var service = container.Resolve<MyService>();

    AssertNamedInstanceWasResolved<IEncryptionProvider>("MyEncryptionProvider");
}