Search code examples
wpfmessagingautofaccaliburn.microeventaggregator

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


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

Solution

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