gpt4 book ai didi

c# - 使用 DryIoc 解决多个注册之一

转载 作者:行者123 更新时间:2023-11-30 21:52:40 26 4
gpt4 key购买 nike

给出下面的小例子,有没有办法在 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

这里消费者根据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# - 使用 DryIoc 解决多个注册之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34612600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com