使用 DryIoc 解决多个注册之一

smo*_*sen 5 c# ioc-container dryioc

给定下面的小例子,有没有办法标记(属性,名称约定,...)中的MyInterface参数MyService2,以便正确解析,或者是传入的唯一方法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>();
    }
}
Run Code Online (Sandbox Code Playgroud)

dad*_*dhi 5

有多种方式:

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

在这里,消费者根据键选择依赖项。

c.Register<MyService2>(made: Made.Of(() => 
    new MyService2(Arg.Of<MyInterface>(ServiceKeys.ImplementationA))));
Run Code Online (Sandbox Code Playgroud)

更新:或以构造函数不可知的方式

c.Register<MyService2>(made:
    Parameters.Of.Type<MyInterface>(ServiceKeys.ImplementationA));
Run Code Online (Sandbox Code Playgroud)

依赖条件

Dependency 根据条件选择消费者:

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

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

它不再是瞬态,但可能没问题,具体取决于您的设置。

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