简体   繁体   中英

Event sourcing implementation with autofac (register/resolve handlers)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM