I needed to apply an aspect to my ASP.NET Web API 2 services on every controller. The trick was that I needed an IDisposable object to be created before the action method executed and then disposed when the action method completed. It’s easy enough to write an ActionFilterAttribute to do something at the beginning or at the end of a controller’s action method being called. But how to you maintain state between the OnActionExecuting and the OnActionExecuted events? That’s what this little snippet does.

And now you wire it up and presto change-o, you’ve got an IDisposable created before execution and disposed after execution. And here’s the simple wire up for global application of the attribute in the Global.asax.cs code: