我正在使用 DryIoc 版本 5.0.0 和 .net 框架,并且我有以下类:
public class AMessageService : IHandle {
public AMessageService (INotify notify) {
//...
}
}
public class BMessageService : IHandle {
public BMessageService (INotify notify) {
//...
}
}
以及以下注册:
// ...
container.Register<IHandle, AMessageService>(serviceKey: nameof(AMessageService));
container.Register<IHandle, BMessageService>(serviceKey: nameof(BMessageService));
// ...
我可以像这样解析构造函数中所有可用的
IHandle
实现:
public SequentialEventAggregator(params IHandle[] handlers) // <-- yields AMessageService and BMessageService
现在我想注册多个 INotify 实现。我想我可以创建一个 NotifyComposite 类来获取 INotify 实现的枚举
public class NotifyComposite: INotify {
private readonly IEnumerable<INotify> _notificators;
public NotifyComposite(IEnumerable<INotify> notificators) {
_notificators = notificators;
}
public Notify():void {
_notificators.ForEach(n => n.Notify());
}
}
// ...
container.Register<IHandle, AMessageService>(serviceKey: nameof(AMessageService));
container.Register<IHandle, BMessageService>(serviceKey: nameof(BMessageService));
container.Register<INotify, NotifyComposite>();
// ...
但现在我被困在尝试注册多个其他具有设置条件的 INotify 实现。
// ...
container.Register<IHandle, AMessageService>(serviceKey: nameof(AMessageService));
container.Register<IHandle, BMessageService>(serviceKey: nameof(BMessageService));
container.Register<INotify, NotifyComposite>();
// using Parent.Parent because the first Parent is NotifyComposite
container.Register<INotify, EmailChannelA>(setup: Setup.With(condition: r => r.Parent.Parent.ImplementationType == typeof(AMessageService));
container.Register<INotify, EmailChannelB>(setup: Setup.With(condition: r => r.Parent.Parent.ImplementationType == typeof(BMessageService)); // <-- does not work properly
container.Register<INotify, ChatChannel>();
// ...
期待
AMessageService
--> 通知是一个 NotifyComposite
,类型为 EmailChannelA
和 ChatChannel
BMessageService
--> 通知是一个 NotifyComposite
,类型为 EmailChannelB
和 ChatChannel
当前结果
AMessageService
--> 通知是一个 NotifyComposite
,类型为 EmailChannelA
和 ChatChannel
BMessageService
--> 通知是一个 NotifyComposite
,类型为 EmailChannelA
和 ChatChannel
其他发现
container.Register<IHandle, AMessageService>(serviceKey: nameof(AMessageService))
后即可工作。似乎,当调用 setup.condition 函数时,解析上下文总是第一个注册的 IHandle
,但我不知道为什么。openResolutionScope
,但这没有帮助Made.Of
和 AMessageService
中使用 BMessageService
会导致重复的代码行,我想避免这种情况。例如。对于所有进一步的 INotify
不依赖于条件并且应该为所有服务注入的实现)如何正确注册?
我解决了这个问题:问题一定是由于缓存和注册
NotifyComposite
而没有进行额外的设置。将 asResolutionCall
或 openResolutionScope
添加到 true
以获得 NotifyComposite
() 会导致所需的行为。
修复:
container.Register<INotify, NotifyComposite>(setup: Setup.With(asResolutionCall: true));