c# – 使用Windsor自动订阅具有自定义功能的事件聚合器

阅读 this博客文章,它提到你可以让你的DI容器自动订阅事件,如果它实现了IHandle<>.这正是我想要完成的.

这是我到目前为止所拥有的.

container.Register(Component
    .For<MainWindowviewmodel>()
    .ImplementedBy<MainWindowviewmodel>()
    .LifeStyle.Transient
    .OnCreate((kernel,thisType) => kernel.Resolve<IEventAggregator>().Subscribe(thisType)));

虽然此代码成功订阅MainWindowviewmodel以接收已发布的消息,但实际接收消息的时间没有任何反应.如果我按预期手动订阅所有工作.

这是我的MainWindowviewmodel类.

public class MainWindowviewmodel : IHandle<SomeMessage>
{
    private readonly Fooviewmodel _fooviewmodel;
    private readonly IEventAggregator _eventAggregator;

    public MainWindowviewmodel(Fooviewmodel fooviewmodel,IEventAggregator eventAggregator)
    {
        _fooviewmodel = fooviewmodel;
        _eventAggregator = eventAggregator;

        //_eventAggregator.Subscribe(this);

        _fooviewmodel.InvokeEvent();
    }

    public void Handle(SomeMessage message)
    {
        Console.WriteLine("Received message with text: {0}",message.Text);
    }
}

如果任何类继承IHandle<&gt ;?,我如何告诉Windsor自动订阅? 我最终想出了这个订阅自定义工具.

public class EventAggregatorFacility : AbstractFacility
{
    protected override void Init()
    {
        Kernel.DependencyResolving += Kernel_DependencyResolving;
    }

    private void Kernel_DependencyResolving(ComponentModel client,DependencyModel model,object dependency)
    {
        if(typeof(IHandle).IsAssignableFrom(client.Implementation))
        {
            var aggregator = Kernel.Resolve<IEventAggregator>();
            aggregator.Subscribe(client.Implementation);
        }
    }
}

查看Caliburn.Micro提供的EventAggregator类,我能够看到订阅成功,但是如果另一个类发布消息,则MainWindowviewmodel类没有得到处理.手动订阅仍然有效,但我想自动执行此过程.我有一种感觉,它没有订阅正确的实例.但不知道如何解决这个问题.

我也尝试过使用Kernel属性公开的所有其他事件.他们中的大多数都无法解析IEventAggregator.

我错过了什么?

解决方法

“I have a feeling that it’s not subscribing the correct instance. Not
sure how to fix that,though.”

您正在订阅实现的类型(System.Type的实例),而不是正在解析的实际依赖项.这条线:

aggregator.Subscribe(client.Implementation);

应该

aggregator.Subscribe(dependency);

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么