1

I implemented Event Sourcing, but i am not sure that i am registering and using the autofac IoC correctly to register and resolve my handlers.

My code:

Example event:

public class AddressChanged : IDomainEvent
{
    public AddressChanged(string address)
    {
        Address = address;
    }

    public string Address { get; set; }
}

Example event handler:

internal class AddressChangedEventHandler : IEventHandler<AddressChanged>
{
    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public void Handle(AddressChanged @event)
    {
        Log.Info($"Address updated to {@event.Address}");
    }
}

Here is how i register my handlers:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
            .AsClosedTypesOf(typeof(IEventHandler<>));

And here is my EventDispatcher class:

public class EventDispatcher : IEventDispatcher
{
    private readonly IComponentContext _context;


    public EventDispatcher(IComponentContext context)
    {
        _context = context;
    }


    public void Dispatch<TEvent>(TEvent @event) where TEvent : IDomainEvent
    {

        dynamic handler = _context.Resolve(typeof(IEventHandler<>).MakeGenericType(@event.GetType()));
        handler.Handle((dynamic)@event);
    }
}

Is this the right way to resolve the handlers with autofac?

IamK
  • 2,753
  • 5
  • 30
  • 39
  • 1
    Maybe this answers your question? https://stackoverflow.com/questions/5629676/using-autofac-with-domain-events – Piotr Oct 17 '17 at 13:24

1 Answers1

0

Yes it was, or at least it worked.

IamK
  • 2,753
  • 5
  • 30
  • 39