danielwertheim

danielwertheim


notes from a passionate developer

Developer that lives by the mantra "code is meant to be shared".

Share


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

Routemeister how to support request response

Daniel WertheimDaniel Wertheim

Currently Routemeister does not come with built in support for a request-response scenario, much because I haven't decided on how this should behave and there hasn't been a need for it yet. But this doesn't stop you from implementing support for it.

Routemeister is asynchronous, hence it relies on the handler to return a Task. Well luckily, Task<T> extends Task. We can use this to our advantage.

Lets take the shipped SequentialAsyncRouter and add one "small" method to it:

public async Task<TResult> RequestAsync<TResult>(object message)  
{
    var messageType = message.GetType();
    var route = _messageRoutes.GetRoute(messageType);
    if (!route.Actions.Any())
        return default(TResult);

    if (route.Actions.Length > 1)
        throw new Exception("The route has more than one action...");

    var envelope = new MessageEnvelope(message, messageType);
    var action = route.Actions[0];
    var resultingTask = (Task<TResult>)action.Invoke(
        _messageHandlerCreator(action.HandlerType, envelope),
        envelope.Message);

    return await resultingTask.ConfigureAwait(false);
}

And there we go, you can now define your handler (remeber you are in control) to support responses:

public interface IMyRequestHandlerOf<in TRequest, TResponse>  
{
    Task<TResponse> HandleAsync(TRequest request);
}

Actually, it works just as well without the response type, but semantics are good so I would define this second interface for defining handlers supporting request-response messaging.

Feel free to comment on if this should be put in Routemeister as is.

Happy routing!

//Daniel

Developer that lives by the mantra "code is meant to be shared".

Comments