A short post with a small, useful tip. It’s mainly for my future self, but may be good to know for you too.

If you’re using ASP.NET Web API, you might have controllers that look like this:

public class CustomerController : ApiController
{
    private readonly ILog _log;

    public CustomerController(ILog log)
    {
        _log = log;
    }

    [HttpGet]
    public HttpResponseMessage GetCustomer(int customerId)
    {
        try
        {
        }
        catch (Exception e)
        {
            _log.Error(e);
            return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
    }
}

Two things can make your code cleaner here:

  • First, use Autofac, you’ll greaty benefit
  • Use the IAutofacExceptionFilter

If you’ve set up Autofac, add this to your builder:

builder.RegisterWebApiFilterProvider(config);

Next, implement the IAutofacExceptionFilter. A simple implementation for the example above could be:

public class ExceptionFilter : IAutofacExceptionFilter
{
    private readonly ILog _log;

    public ExceptionFilter(ILog log)
    {
        _log = log;
    }

    public void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        _log.Error(actionExecutedContext.Exception);
        actionExecutedContext.Response =
            actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, actionExecutedContext.Exception);
    }
}

Now, register that filter:

builder.RegisterType<ExceptionFilter>()
    .AsWebApiExceptionFilterFor<CustomerController>()
    .InstancePerRequest();

Now, you can remove the dependency to ILog in your controller, and you can remove the ugly try-catch blocks. Next, I’ll show you how to integration test this.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.