Home
Atom Feed

Missing Ninject bindings causes WebApi to fail silently

I noticed this problem this week when I started to receive 500 Internal Server Errors on an ApiController I just made.

The weird thing was that I had implemented logging in the Application_Error event in Global.asax, but nothing happened was logged. Debugging the application revealed that the event was not hit at all. I even tried implementing an ExceptionFilterAttribute filter, but it never got hit either.

Turned out I had a missing Ninject binding. I had constructor parameter (IStorageRepository) in my controller that was not bound to a concrete implementation. Adding the implementation solved the problem, but since this api is going to grow a lot bigger I needed to find a solution that would let me know if I forgot something like this in the future.

Enter Ninject.Web.WebApi.MissingBindingLogger. (Also available as a NuGet package)
This extension uses the logger of your choice (as long as it uses the Ninject logging extensions) and writes an error message to your log each time your application tries to use a dependency that has not been bound to a concrete class.

It also provides you with an event you can subscribe to; MissingBindingLogger.BindingMissing .
You can then (for example) use the included MissingBindingException class to execute custom code every time a binding is missing.

Example [Throw exception when binding is missing]:

MissingBindingLogger.BindingMissing += OnBindingMissing;

    ...

public void OnBindingMissing(object sender, MissingBindingEventArgs args)
{
    throw new MissingBindingException(args.Service);
}

I hope this package saves you from spending several hours debugging and searching for an invisible error like I did. :-)