I needed to publish a message across the ESB (MassTransit) that will return a different type of object depending on how the message is processed. I wanted to implement this in a generic way so I could wire up other services with similar requirements in the same way.
Publish a request
public IGenericResponse<TPayload> PublishRequest<TMessage, TPayload>(TMessage message, Type[] potentialResponseTypes)
where TMessage : class
{
IGenericResponse<TPayload> commandResult = null;
_bus.PublishRequest(message, c =>
{
foreach (Type responseType in potentialResponseTypes)
{
Type genericHandler = typeof(GenericHandler<,>).MakeGenericType(new[]{ responseType, typeof(TMessage)});
var handler = new Action<object>(result =>
{
commandResult = (IGenericResponse<TPayload>) result;
});
Activator.CreateInstance(genericHandler, new object[] {c, handler});
}
c.SetTimeout(10.Seconds());
});
return commandResult;
}
Generic Handler to wire it up
internal class GenericHandler<TPayload, TMessage>
where TMessage : class
where TPayload : class
{
public GenericHandler(InlineRequestConfigurator<TMessage> configurator, Action<object> handler)
{
configurator.Handle<GenericResponse<TPayload>>(handler);
}
}
Thoughts?