Today we will talk about Web API and Unity Dependency Injection Container.
Web API is great technology for building RESTful API-s.
For my projects I always use Dependency Injection.
The advantages are many but one of the main for me is that I can efficiently unit test my code and be sure that new changes are not breaking the existing logic.
I think Dependency Injection is must for every project becuase of the wide use of this design pattern, today we have various tools called Dependency Injection Containers.
Dependency Injection Containers simplify the mapping between interfaces and their concrete implementations in the context of Dependency Injections.
They are very handy because take care for initializing instances based on your configuration
And this is fine but it will not work as expected.
You will get strange error for missing parameter less constructor for your controllers. And even if you add one, it will be used by Web API when creating your controllers so none of your dependencies that you pass with constructor will be initialized and you will end up with null reference exceptions later in the action methods.
For simplifying the additional work you need to do, the best approach is too install one more nuget package – Unity bootstrapper for ASP.NET Web API
Unity bootstrapper for ASP.NET Web API will add additional class where you can register mappings between interfaces and concrete implementations and a little bit of configuration that will give you the expected result.
Now your controllers will use the expected constructors and the dependencies will be resolved based on your configuration.
If you are building MVC application there is an alternative package – Unity bootstrapper for ASP.NET MVC
Unity bootstrapper for ASP.NET MVC will make the integration of Unity Container a lot easier with MVC solution.
Have a great day!