Caliburn.Micro. Automatically call eventaggregator.Subscribe() for IHandle implementors with Autofac

纵饮孤独 提交于 2019-11-30 13:49:00
Nicholas Blumhardt

Making a few assumptions about how Caliburn works, I think what you're looking for is:

builder.RegisterType<MyViewModel>();
builder.RegisterModule<AutoSubscribeHandlersModule>();

Where the module is implemented something like:

class AutoSubscribeHandersModule : Module
{
    protected override AttachToComponentRegistration(
        IComponentRegistry registry,
        IComponentRegistration registration)
    {
        if (typeof(IHandle).IsAssignableFrom(registration.Activator.LimitType))
        {
            registration.Activated += (sender, e) => {
                var aggregator = e.Context.Resolve<IEventAggregator>();
                aggregator.Subscribe((IHandle)e.Instance);
            };
        }
    }
}

This is an old post, but I thought I would just add a note to it.

You can use the constructor in Autofac to inject handlers:

public MessageDispatcher(IEnumerable<IHandler> handlers)
{
    foreach (var handler in handlers)
        Subscribe(handler);
}

While the above isn't the EventAggregator base class from Caliburn.Micro, you can sub-class it, or alter the source code to provide your own constructor for the EventAggregator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!