title: Autofac resolve all EventHandlers of abstract base class
body: <p>Hi Some how I cannot find the answer to this problem:
  I Have event handler ala:</p>
  
  <pre><code>public class MyEvenHandler : EventHandler&lt;MyEvent&gt;
  </code></pre>
  
  <p>Where EventHandler is an abstract class</p>
  
  <pre><code> public abstract class EventHandler&lt;TEvent&gt; : IEventHandler&lt;TEvent&gt;
      where TEvent : IDomainEvent 
  </code></pre>
  
  <p>And</p>
  
  <pre><code>public interface IEventHandler&lt;in TEvent&gt; : IEventHandler where TEvent : IDomainEvent
  {
      bool Handles(IDomainEvent @event);
      void Handle(TEvent @event);
      Task HandleAsync(TEvent @event);
  }
  </code></pre>
  
  <p>I Register with autofac like this:</p>
  
  <pre><code>var builder = new ContainerBuilder();
  
  builder.RegisterSource(new ContravariantRegistrationSource());
  </code></pre>
  
  <p>...</p>
  
  <pre><code>builder.RegisterAssemblyTypes(commandsAssemblies)
              .AsClosedTypesOf(typeof(EventHandler&lt;&gt;))
              .AsImplementedInterfaces()
              .InstancePerRequest();
  </code></pre>
  
  <p>Now I want to resolve all eventhandlers and register them with a messageDispatcher class</p>
  
  <pre><code>var handlers = e.Context.Resolve&lt;IEnumerable&lt;IEventHandler&lt;IDomainEvent&gt;&gt;&gt;().ToList();
  
  var handlers2 = e.Context.Resolve&lt;IEnumerable&lt;IEventHandler&lt;PolicyCreated&gt;&gt;&gt;().ToList();
  </code></pre>
  
  <p>the handlers variable is empty...
  handlers2 resolves correctly. But I would like to resolve all handlers genericly</p>
  
  <p>the messageDispatcher (eventDispathcer) look like this:</p>
  
  <pre><code>public class EventDispatcher : IEventDispatcher
  {
      private readonly IList&lt;IEventHandler&gt; _eventHandlers = new List&lt;IEventHandler&gt;();
  
      public virtual void RegisterEventHandler(IEventHandler eventHandler)
      {
          _eventHandlers.Add(eventHandler);
      }
  
      public virtual IMessageResults Publish&lt;TEvent&gt;(TEvent @event) where TEvent : IDomainEvent
      {
          var result = new MessageResults();
          var handlers = _eventHandlers;
  
          if (handlers == null)
          {
              Trace.WriteLine(String.Format("No event handlers for event {0} ", typeof(TEvent)));
  
              result.AddResult(new MessageResult(true));
              return result;
          }
  
          foreach (var eventHandler in handlers.Where(h =&gt; h.Handles(@event as IDomainEvent)))
          {
              eventHandler.Handle(@event);
          }
          return result;
      }
  
      public int EventHandlerCount
      {
          get
          {
              return _eventHandlers.Count();
          }
      }
  }
  </code></pre>
  
  <p>To summarize goals:</p>
  
  <ol>
  <li>use assembly scanning</li>
  <li>resolve to IEnumerable of implementations of EventHandler</li>
  </ol>