tsJensen

A quest for software excellence...

ASP.NET Web API and IDisposable Aspect with ActionFilterAttribute

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.

public class DisposableActionFilterAttribute : ActionFilterAttribute
{
  private readonly IDisposableProvider _provider;

  public DisposableActionFilterAttribute()
  {
    _provider = IoC.Instance.Container.Resolve<IDisposableProvider>();
  }

  public override void OnActionExecuting(HttpActionContext actionContext)
  {
    base.OnActionExecuting(actionContext);
    IDisposable obj = _provider.CreateDisposableObjectMethod() as IDisposable;
    actionContext.Request.Properties[Consts.DisposableObjectPropertyKey] = obj;
  }

  public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
  {
    base.OnActionExecuted(actionExecutedContext);
    IDisposable obj = actionExecutedContext.Request.Properties[Consts.DisposableObjectPropertyKey]
      as IDisposable;
    if (null != obj) obj.Dispose();
  }
}

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:

public class WebApiApplication : System.Web.HttpApplication
{
  protected void Application_Start()
  {
    //..
    GlobalConfiguration.Configuration.Filters.Add(
      new DisposableActionFilterAttribute());
    //..

I do realize there are many examples of the ActionFilterAttribute and this technique, but it’s easier to search my own blog later when I need to remember how to do this. Happy Monday!