Using Unity DI with Angular + WebAPI

Unity is a Dependency Injection container. Our objective usage of Unity framework is to inject the dependencies to the dependent object. 

The Dependency Injection pattern is an implementation of Inversion of Control. IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source.

The advantages of using Dependency Injection pattern and Inversion of Control are the following:

  • Reduces class coupling
  • Increases code reusing
  • Improves code maintainability
  • Improves application testing

Unity has an excellent documentation and support for Unity WebAPI. Unity DI is open sourced, more info here at https://github.com/unitycontainer/unity

For this demo, we have a multilayered project, whose solution looks like below

Our first step is to add Unity.WebApi to TrackerFrontEnd is via the NuGet package. You can search for unity.webapi using the GUI or type the following into the package manager console.

Install-Package Unity
install-package Unity.WebApi

Once we have installed Unity on our main project, our reference would have added required Unity packages.

Second step is to go to, web application startup.cs file and register components using unity.

Hooking them up.
Once installed the NuGet package, we need to hook it up in order to get the framework to start resolving components via Unity. The old school way, involved calling Bootstrapper.Initialise(). For the new packages, we just change this line to UnityConfig.RegisterComponents(). Once UnityConfig has registered components, it is easy for us to start registering our interfaces types with actual implementations.

Now, post hooking up Unity DI, we can inject dependencies into any controller. I prefer using constructor injection.

Advertisements