I am writing a simple event dispatcher where my events come in as objects with the clr type name and the json object representing the original event (after the byte[] has been processed into the jobject) that was fired. I'm using GetEventStore if anyone wants to know the specifics.
I want to take that clr type to do 2 things:
I have managed to get part 1 working fine with the following code:
var processedEvent = ProcessRawEvent(@event);
var t = Type.GetType(processedEvent.EventClrTypeName);
var type = typeof(IHandlesEvent<>).MakeGenericType(t);
var allHandlers = container.ResolveAll(type);
foreach (var allHandler in allHandlers)
{
var method = allHandler.GetType().GetMethod("Consume", new[] { t });
method.Invoke(allHandler, new[] { processedEvent.Data });
}
ATM the issue is that processedEvent.Data is a JObject - I know the type of processedEvent.Data because I have t defined above it.
How can I parse that JObject into type t without doing any nasty switching on the type name?
Use ToObject
:
var data = processedEvent.Data.ToObject(t);
or if you have a known type then:
MyObject data = processedEvent.Data.ToObject<MyObject>();