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?
Yes it was, or at least it worked.