使用 DryIoc 解决多个注册之一

Resolve one of multiple registrations with DryIoc

给出下面的小例子,有没有办法标记(属性,名称约定,...)MyService2 中的 MyInterface 参数,以便它能够正确解析,或者是传入 MyInterface[] 的唯一方法? 我知道 Castle Windsor 可以根据命名约定来解析它,但是我在 DryIoc 中没有找到类似的东西

public interface MyInterface { }

public class MyImplementationA : MyInterface { }

public class MyImplementationB : MyInterface { }

public class MyService1
{
    public MyService1(MyInterface[] implementations) {
        Console.WriteLine(implementations.GetType().Name);
    }
}

public class MyService2
{
    public MyService2(MyInterface implementationA) {
        Console.WriteLine(implementationA.GetType().Name);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var c = new Container();
        c.Register<MyInterface, MyImplementationA>(serviceKey: "implementationA");
        c.Register<MyInterface, MyImplementationB>(serviceKey: "implementationB");

        c.Register<MyService1>();
        c.Register<MyService2>();

        var a = c.Resolve<MyService1>();
        var b = c.Resolve<MyService2>();
    }
}

有多种方式:

首先使用您评论中的服务密钥

这里消费者根据key选择依赖。

c.Register<MyService2>(made: Made.Of(() => 
    new MyService2(Arg.Of<MyInterface>(ServiceKeys.ImplementationA))));

更新: 或与构造函数无关的方式

c.Register<MyService2>(made:
    Parameters.Of.Type<MyInterface>(ServiceKeys.ImplementationA));

依赖条件

依赖根据条件选择消费者:

c.Register<MyInterface, MyImplementationA>(setup: Setup.With(
    condition: request => request.Parent.ServiceType == typeof(MyService2)));

依赖在特定消费者的解析范围内被重用

它将不再是 Transient,但根据您的设置可能没问题。

c.Register<MyService2>(setup: Setup.With(openResolutionScope: true));
c.Register<MyInterface, MyImplementationA>(Reuse.InResolutionScopeOf<MyService2>());

您的注册成功

c.Register<MyInterface, MyImplementationA>(serviceKey: "implementationA");
c.Register<MyInterface, MyImplementationB>(serviceKey: "implementationB");

如果您想解析 A 或 B 的具体 实例,您可以通过以下方式更轻松地实现:

var a = c.Resolve<MyInterface>(serviceKey: "implementationA");
var b = c.Resolve<MyInterface>(serviceKey: "implementationB");