Caliburn.Micro.使用Autofac自动为IHandle实现者调用eventaggregator.Subscribe() [英] Caliburn.Micro. Automatically call eventaggregator.Subscribe() for IHandle implementors with Autofac

查看:138
本文介绍了Caliburn.Micro.使用Autofac自动为IHandle实现者调用eventaggregator.Subscribe()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Caliburn.Micro 文档中,作者提到了这种可能性:

In Caliburn.Micro documentation the authors mention such possibility:

文档链接

IHandle继承自标记接口IHandle.这允许使用强制转换来确定对象实例是否订阅了任何事件.如果您与IoC容器集成,则可以进行简单的自动订阅.大多数IoC容器(包括SimpleContainer)都提供一个在创建新实例时被调用的钩子.只需连接容器的回调,检查正在创建的实例,看看它是否实现了IHandle,如果确实实现了,则在事件聚合器上调用Subscribe.

IHandle inherits from a marker interface IHandle. This allows the use of casting to determine if an object instance subscribes to any events. This enables simple auto-subscribing if you integrate with an IoC container. Most IoC containers (including the SimpleContainer) provide a hook for being called when a new instance is created. Simply wire for your container’s callback, inspect the instance being created to see if it implement IHandle, and if it does, call Subscribe on the event aggregator.

如何用Autofac做到这一点?

How is it possible to achieve this with Autofac?

我尝试利用装饰器的功能,但是对于这种情况当然是不合适的.而且,默认情况下,我的 IHandle<> 的实现者不会在容器中注册为 IHandle 的实例.

I tried to utilize the features of decorator, but of course it's kinda improper for this case. More over, by default my implementors of IHandle<> are not getting registered as instances of IHandle within the container.

PsS .提供此不当的实施方式是为了以防万一,尽管我对此表示怀疑.

P.S. Providing this improper implementation just in case it might be of any use, though I doubt.

builder.RegisterInstance<IEventAggregator>(new EventAggregator());
builder.RegisterDecorator<IHandle>((container, handler) =>
{
    var eventAggregator = container.Resolve<IEventAggregator>();
    eventAggregator.Subscribe(handler);
    return handler;
}, "unsubscribed", "subscribed");

推荐答案

对Caliburn的工作原理做一些假设,我认为您正在寻找的是:

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

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

模块的实现方式如下:

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);
            };
        }
    }
}

这篇关于Caliburn.Micro.使用Autofac自动为IHandle实现者调用eventaggregator.Subscribe()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆