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

查看:46
本文介绍了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.

P.S. 提供这个不正确的实现,以防万一它可能有用,尽管我怀疑.

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天全站免登陆