我目前正在从事一个大量使用统一子容器的项目。整个系统是事件驱动的,我想自动化事件订阅。
所有事件处理程序均由Unity注册/创建。所以我基本上想做的是:每当事件处理程序解决后,都自动将其订阅到事件。我想出了一个扩展名,可以正常工作:
internal class MessageSubscriptionUnityExtension : UnityContainerExtension, IBuilderStrategy
{
private ConcurrentDictionary<IHandleEvents, IDisposable> subscriptions = new ConcurrentDictionary<IHandleEvents, IDisposable>();
protected override void Initialize()
{
this.Context.Strategies.Add(this, UnityBuildStage.PostInitialization);
}
public void PreBuildUp(IBuilderContext context)
{
}
public void PostBuildUp(IBuilderContext context)
{
if (context.Existing is IHandleEvents eventHandler)
{
var eventDistributor = this.Container.Resolve<IDistributeEvents>();
this.subscriptions.TryAdd(eventHandler, eventDistributor.SubscribeAllEventsHandledBy(eventHandler));
}
}
public void PreTearDown(IBuilderContext context)
{
}
public void PostTearDown(IBuilderContext context)
{
}
}
退订仍然丢失(这就是字典的目的)。
但这是问题所在:我想将此扩展的范围限制为添加到其中的(子容器)。
示例(伪代码):
internal class Handler1 : IHandleEvents<SomeEvent>
{
public void HandleAsync(SomeEvent eventMessage)
{
// do something
}
}
internal class Handler2 : IHandleEvents<SomeEvent>
{
public void HandleAsync(SomeEvent eventMessage)
{
// do something
}
}
var parent = new UnityContainer();
parent.RegisterType<Handler1>();
var child = parent.CreateChildContainer();
child.AddNewExtension<MessageSubscriptionUnityExtension>();
child.RegisterType<Handler2>();
parent.Resolve<Handler1>(); // Should not subscribe
parent.Resolve<Handler2>(); // Should not work at all
child.Resolve<Handler1>(); // Should not subscribe
child.Resolve<Handler2>(); // Only this should automatically subscribe the event.
但是对于在父容器中注册的类型也调用PostBuildUp。
可能我只是用错了。谁能指出我正确的方向?这不应该那么难:)