Wednesday, February 12, 2014

Web API 2.1 Global Exception Handling is missing IoC integration

Web API 2.1 brings a lot of great new features to the table. One of them is global error handling, allowing you to log all unhandled exceptions through one central mechanism

This is a sample from the Web Api documentation:

The annoying thing I noticed is that the IExceptionLogger interface is not resolved through the dependency injection integration mechanism that Web API offers out-of-the-box. So you explicitly have to register your implementation through the Services property on the HttpConfiguration object. Bedroefde emoticon

Hopefully the Web API team will change this in the future...

1 comment:

Shtin said...

Actually it does. You just need to register it a proper way. When WebAPI resolves IExceptionLogger it actually calls for GetServices (not GetService). This means that you need to register IEnumerable not IExceptionLogger. With SimpleInjector it looks like this:
container.RegisterCollection(new [] { typeof(MyExceptionLogger) });
And handler is a single object:
container.Register();