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

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

概述阅读 this博客文章,它提到你可以让你的DI容器自动订阅事件,如果它实现了IHandle<>.这正是我想要完成的. 这是我到目前为止所拥有的. container.Register(Component .For<MainWindowViewModel>() .ImplementedBy<MainWindowViewModel>() .LifeStyle.Transient 阅读 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);
总结

以上是内存溢出为你收集整理的c# – 使用Windsor自动订阅具有自定义功能的事件聚合器全部内容,希望文章能够帮你解决c# – 使用Windsor自动订阅具有自定义功能的事件聚合器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1243229.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存