当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-22
我有以下片段: static void Main(string[] args) { var container = new UnityContainer(); container.RegisterTypeIConnection, SerialPortConnection("SerialConnection"); container.RegisterTypeIConnection, ParallelPortConnection("ParallelCo
我有以下片段:

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

我想在两个不同的名称下注册类型设备,因此根据请求的名称,设备实例将使用适当的连接进行初始化.以下是解决此问题的一种方法,仅用于演示:

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");
你可以这样做:

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");
}
网友评论