Unity Container: What was wrong with this code?

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

SampeCodeWithUnity

My question to him: What is wrong with that code?

And his answer: Due to from best practice from this post:

http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

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.

  1. 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.
  2. 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.

  1. Harrison Le

    Your suggestion is fine. But in some special minor cases, if you didn’t avoid this , you would pay for your SLA ‘ product. You imagine you had the high traffic online payment website. What happens if your IoC container has problems in the completion payment step ? You don’t catch in providing IoC step while it is easy recovery and your website always shows the failed notice. Your customers will angry because they has charged complete. They don’t care what wrong in your website. they only know they lost the money. In fact, some pain points must be paid for this reason. With my experience, we need to try catch in minor components that you can easy recovery but your code. Otherwise, you can write your custom exception, and then you log this information to track the issue without annoying customer.

    • thaianhduc

      Thank you for your deep look at it 🙂 I agree with your point. My suggestion is for mostly general cases and most of the application i wrote so far. For each application type, we will have specific implementation that will consider Pros and Cons.

Write a Comment

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

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