Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing IRequestContext on a plugin on ServiceStack

I'm trying to create a plugin based on ServiceStack IPlugin interface that can measure the time elapsed on the operations and publish it to a dashboard. The code itself would be quite simple and I tried to do it based on some concepts on the Request Logger.

This logger uses a StopWatch that is added inside the default ServiceRunner class, but it only does it when the Request Logger is configured.

I already have a custom ServiceRunner and the StopWatch is being initialized there but using this approach isn't optimal since the plugin is not self-contained.

My biggest issue now is that I apparently can't access the IRequestContext. Is there any way an plugin can access this context or any other way to measure the time to run the requests inside a simple plugin, not depending on a ServiceRunner?

Thanks!

like image 719
rocco Avatar asked Aug 21 '13 21:08

rocco


1 Answers

Store the start time on the request in a RequestFilter and then in a ResponseFilter calculate the time using the current time minus the start time?

This can be done in a plugin too.

Here's some pseudo code...

appHost.RequestFilters.Add( ( req, res, obj ) =>
    {
        if(!req.Items.ContainsKey( "begin-time" ) )
            req.Items.Add( "begin-time", DateTime.Now );
        else
            req.Items[ "begin-time" ] = DateTime.Now;
    }
);

appHost.ResponseFilters.Add( ( req, res, i ) =>
    {
        var beginTime = (DateTime)req.Items[ "begin-time" ];

        var elapsed = DateTime.Now - beginTime;
    }
);
like image 166
kinstephen Avatar answered Oct 19 '22 18:10

kinstephen