Recently, I reviewed code from a candidate. He wrote a simple Web Application using WebApi. And he used Unity as IoC Container. And this is part of the code I asked him the question
My question to him: What is wrong with that code?
And his answer: Due to from best practice from this post:
And it is good to use suggestion implementation from Mike Wasson. However, I think he should think a little deeper with my question.
Anyway, I think it is interesting to explain my answer here.
- Exception handling: When the unity cannot resolve a component, and throw that exception, how to know: WHY? There is something wrong with your code. And you just assume it will be null and move on. Most of the time, the container should tell us why it cannot resolve a component. In the windsor container world, most of the time, it is lacking of component registered.
- About caller code: With that resolve strategy (return null on failed), the caller code have to check for null every time. Else you have a chance to get: NullReferenceException. Which means you introduce the unstable in your code, and the chance to debug it – in production code.
My suggestion: Lets it failed and throw exception. And you should have a error handler in the application scope.