IoTSharp / MQTTnet.AspNetCore.Routing

Easily create Controllers and Actions to process incoming MQTT messages using a familiar paradigm and MQTTnet

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature Request | Support for intercepting method invocations

jfrancke opened this issue · comments

Describe the feature request

I would like to be able to more easily do request- and performance logging of the controller methods. One way to generically implement this, could be to add support for an 'route invocation interceptor' that are called before- and after the controller method is invoked in the MqttRouter. This could allow for many different use cases apart from logging.

Describe the solution you'd like

In program.cs I would like the ability to configure .WithRouteInvocationInterceptor() with an type-reference to IRouteInvocationInterceptor that can be resolved via dependency injection.

public interface IRouteInvocationInterceptor {
    /// <summary>
    /// Executed before the route handler is executed
    /// </summary>
    /// <param name="clientId">The identifier of sender of the message</param>
    /// <param name="applicationMessage">The message being handled</param>
    /// <returns>Returns an opague object that may be used to correlate before- and after route execution. May be null</returns>
    Task<object?> RouteExecuting( string clientId, MqttApplicationMessage applicationMessage );
    
    /// <summary>
    /// Executed after the route handler has been executed.
    /// </summary>
    /// <param name="o">Set to the the response of <see cref="RouteExecuting(string, MqttApplicationMessage)"/>. May be null.</param>
    /// <param name="ex">An exception if the route handler failed. Otherwise null.</param>
    /// <returns></returns>
    Task RouteExecuted(object? o, Exception? ex);
}

If the interceptor is configured, it should be called in the MqttRouter.OnIncomingApplicationMessage method.

Describe alternatives you've considered

The alternative, currently, is to add logging to each individual controller method which is tedious and potentially error prone.

Please note

Please note that all names are purely suggestions ;)

Hey guys - I noticed that you made the new release available today, so I just had a quick play-around with it.
I noticed that the interceptor.RouteExecuted will only be called if the execution fails (an exception is thrown) - I would like for it to be executed regardless (meaning that the ex argument could be null on success). This will enable my use-case where I need to log the execution time of the controller method. Sorry for not being more clear :)