Close

August 23, 2016

Autofac, Web API and filters

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:

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:

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

Now, register that filter:

Now, you can remove the dependency to ILog in your controller, and you can remove the ugly try-catch blocks.

Leave a Reply

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