lundi 2 mai 2016

Effective way to invoke generic interface method in runtime

I'm working on the some kind of EventSourcing architecture and have 2 main concepts in my app - events and handlers.

Events example:

class NewRecordCreated: EventMessage {...}

And there some handlers looks like:

class WriteDBHandler: IEventHandler<NewRecordCreated>, IEventHandler<RecordUpdated> { 
    public void Handle(NewRecordCreated eventMessage) {...}
    public void Handle(RecordUpdated eventMessage) {...} 
}

And also I have custom implementation of queue protocol which dispatch events to proper handlers. So basically on app startup I parse assembly and create mapping between event and handlers based on types.

So when I actually dispatching events to handlers I based on event type getting chain of handler's types - something like var handlerChain = [typeof(WriteDbHandler), typeof(LogHandler), typeof(ReadModelUpdateHandler)] and for each of those handlers I need to invoke it's instance, then cast it to proper interface (IEventHandler<>) and than invoke Handle method.

But I can't cast to generic interface, since it's not possible. I think about options of implementing non generic version of interface, but it's seems quite unpleasant for me to add extra method implementation each time, especially if there no any real reasons for it.

I think about dynamic invocation or reflection, but both of this variants seems have performance issues. Maybe you could advice me some suitable alternatives?





Aucun commentaire:

Enregistrer un commentaire