问题
In Caliburn.Micro documentation the authors mention such possibility:
documentation link
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.
How is it possible to achieve this with Autofac?
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. 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");
回答1:
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);
};
}
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/6871077/caliburn-micro-automatically-call-eventaggregator-subscribe-for-ihandle-imple