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

2

8

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");
Allegro answered 29/7, 2011 at 9:22 Comment(0)
W
15

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);
            };
        }
    }
}
Whitelivered answered 29/7, 2011 at 9:55 Comment(2)
Doh, again beaten at the finish line! :)Treenatreenail
It really satisfies my current needs. Thanks!Allegro
U
0

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.

Undercool answered 13/1, 2017 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.