问题描述
在 Caliburn.Micro 文档中,作者提到了这种可能性:
In Caliburn.Micro documentation the authors mention such possibility:
如何用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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!