RESTful Day 2: Inversion of Control Using Dependency Injection in Web API's Using Unity Container and Bootstrapper

Introduction

This article explains how to make our Web API service architecture loosely coupled and more flexible. We already learned how to create a RESTful service using the ASP.Net Web API and Entity framework in my last article. If you remember, we ended up with a solution with a design flaw, we'll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.

Image source : https://www.pehub.com/wp-content/uploads/2013/06/independent-300x200.jpg

There are various methods you can use to resolve dependency of components. In my this article I'll explain how to resolve a dependency using Unity Container provided by Microsoft's Unity Application Block.

We'll not go into very detailed theory, for theory and understanding of DI and IOC you can use the following links : Unity and Inversion of Control(IOC). We'll straight away jump into a practical implementation.

Roadmap

Our roadmap for learning RESTful APIs remains the same; it is:

 
 

I'll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are a few implementations that are very hard to find in .NET Framework 4.0, but I'll make it easy by showing how to do it.

Existing Design and Problem

We already have an existing design. If you open the solution, you'll get to see the structure as shown below.

The modules are dependent in a way,

There is no problem with the structure, but the way they interact with each other is really problematic. You must have noticed that we are trying to communicate with layers, making the physical objects of classes.

For example, the Controller's constructor makes an object of the Service layer to communicate as in the following:

 

  1. /// <summary>  
  2. /// Public constructor to initialize product service instance  
  3. /// </summary>  
  4. public ProductController()  
  5. {  
  6.     _productServices =new ProductServices();  
  7. }  

The Service constructor in turn makes an object of UnitOfWork to communicate with the database as in the following:

  1. /// <summary>  
  2. /// Public constructor.  
  3. /// </summary>  
  4. public ProductServices()  
  5. {  
  6.     _unitOfWork = new UnitOfWork();  
  7. }  

The problem lies in these portions of code. We see the Controller is dependent upon instantiation of the service and the service is dependent upon UnitOfWork to be instantiated. Our layers should not be that tightly coupled and should be dependant on each other.

The work of creating an object should be assigned to someone else. Our layers should not worry about the creation of objects.

We'll assign this role to a third-party that will be called our container. Fortunately Unity provides that help to us, to eliminate this dependency problem and invert the control flow by injecting a dependency, not by creating objects but by using constructors or properties. There are other methods too, but I am not going into detail.

Introduction to Unity

You can have a read about Unity from this link, I am just quoting some lines.

Image source: http://img.tradeindia.com/fp/1/669/664.jpg

“The Unity Application Block (Unity) is a lightweight, extensible dependency injection container that supports constructor injection, property injection and method call injection. It provides developers with the following advantages:

  • It provides simplified object creation, especially for hierarchical object structures and dependencies that simplifies application code.
  • It supports abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns.
  • It increases flexibility by deferring component configuration to the container.
  • It has a service location capability; this allows clients to store or cache the container. This is especially useful in ASP.NET Web applications where developers can persist the container in the ASP.NET session or application.”
Setup Unity

Open your Visual Studio, I am using Visual Studio 2010, you can use Visual Studio version 2010 or above. Load the solution.

Step 1

Browse to Tools -> Library Packet Manager - > Packet Manager Console as in the following:

We'll add a package for a Unity Application Block.

In the bottom-left corner of Visual Studio, you'll find where to write the command.

Type command Unity.MVC3 and choose “WebApi” project before you fire the command.

Step 2

Now for the Bootstrapper class.

Unity.MVC3 comes with a Bootstrapper class. As soon as you run the command, the Bootstrapper class will be generated in your WebAPI project as in the following:

  1. using System.Web.Http;  
  2. using System.Web.Mvc;  
  3. using BusinessServices;  
  4. using DataModel.UnitOfWork;  
  5. using Microsoft.Practices.Unity;  
  6. using Unity.Mvc3;  
  7.   
  8. namespace WebApi  
  9. {  
  10.     public static class Bootstrapper  
  11.     {  
  12.         public static void Initialise()  
  13.         {  
  14.             var container = BuildUnityContainer();  
  15.   
  16.             DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
  17.   
  18.             // register dependency resolver for WebAPI RC  
  19.             GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);  
  20.         }  
  21.   
  22.         private static IUnityContainer BuildUnityContainer()  
  23.         {  
  24.             var container = new UnityContainer();  
  25.   
  26.             // register all your components with the container here  
  27.             // it is NOT necessary to register your controllers  
  28.               
  29.             // e.g. container.RegisterType<ITestService, TestService>();          
  30.             container.RegisterType<IProductServices, ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());  
  31.   
  32.             return container;  
  33.         }  
  34.     }  
  35. }  

This class comes with an initial configuration to set up your container. All the functionality is builtin, we only need to specify the dependencies that we need to resolve in the “BuildUnityContainer”, like it says in the commented statement as in the following:

  1. // register all your components with the container here  
  2. // it is NOT necessary to register your controllers  
  3.   
  4. // e.g. container.RegisterType<ITestService, TestService>();          

Step 3

Just specify the components below these commented lines that we need to resolve. In our case, it's ProductServices and UnitOfWork, so just add:

 

  1. container.RegisterType<IProductServices, ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());  

"HierarchicalLifetimeManager" , for this lifetime manager, as for the ContainerControlledLifetimeManager, Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. The distinction is that when there are child containers, each child resolves its own instance of the object and does not share one with the parent. When resolving in the parent, the behavior is like a container controlled lifetime; when resolving the parent and the child you have different instances with each acting as a container-controlled lifetime. If you have multiple children, each will resolve its own instance.

If you don't find “UnitOfWork”, just add a reference to the DataModel project in the WebAPI project.

So our Bootstrapper class becomes:

  1. public static class Bootstrapper  
  2. {  
  3.     public static void Initialise()  
  4.     {  
  5.         var container = BuildUnityContainer();  
  6.   
  7.         DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
  8.   
  9.         // register dependency resolver for WebAPI RC  
  10.         GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);  
  11.     }  
  12.   
  13.     private static IUnityContainer BuildUnityContainer()  
  14.     {  
  15.         var container = new UnityContainer();  
  16.   
  17.         // register all your components with the container here  
  18.         // it is NOT necessary to register your controllers  
  19.           
  20.         // e.g. container.RegisterType<ITestService, TestService>();          
  21.         container.RegisterType<IProductServices, ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());  
  22.   
  23.         return container;  
  24.     }  
  25. }

Like that we can also specify other dependent objects in BuildUnityContainerMethod.

Step 4

Now we need to call the Initialise method of the Bootstrapper class. Note, we need the objects as soon as our modules load, therefore we require the container to do its work when the application loads, therefore go to the Global.asax file and add one line to call the Initialise method. Since this is a static method, we can directly call it using the class name as in the following:

  1. Bootstrapper.Initialise();  

Our global.asax becomes,

  1. using System.Linq;  
  2. using System.Web.Http;  
  3. using System.Web.Mvc;  
  4. using System.Web.Optimization;  
  5. using System.Web.Routing;  
  6. using Newtonsoft.Json;  
  7. using WebApi.App_Start;  
  8.   
  9. namespace WebApi  
  10. {  
  11.     // Note: For instructions on enabling IIS6 or IIS7 classic mode,   
  12.     // visit http://go.microsoft.com/?LinkId=9394801  
  13.   
  14.     public class WebApiApplication : System.Web.HttpApplication  
  15.     {  
  16.         protected void Application_Start()  
  17.         {  
  18.             AreaRegistration.RegisterAllAreas();  
  19.   
  20.             WebApiConfig.Register(GlobalConfiguration.Configuration);  
  21.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  22.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  23.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  24.             //Initialise Bootstrapper  
  25.             Bootstrapper.Initialise();  
  26.   
  27.             //Define Formatters  
  28.             var formatters = GlobalConfiguration.Configuration.Formatters;  
  29.             var jsonFormatter = formatters.JsonFormatter;  
  30.             var settings = jsonFormatter.SerializerSettings;  
  31.             settings.Formatting = Formatting.Indented;  
  32.             // settings.ContractResolver = new CamelCasePropertyNamesContractResolver();  
  33.             var appXmlType = formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");  
  34.             formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);  
  35.   
  36.             //Add CORS Handler  
  37.             GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());  
  38.         }  
  39.     }  
  40. }  

Half of the job is done. We now need to touch base with our controller and service class constructors to utilize the instances already created for them at application load.

Setup Controller

We have already set up Unity in our application. There are various methods in which we can inject a dependency, like constructor injection, property injection, via a service locator. I am here using Constructor Injection, because I find it the best method to use with Unity Container to resolve dependency.

Just go to your ProductController, you find your constructor written as:

  1. /// <summary>  
  2. /// Public constructor to initialize product service instance  
  3. /// </summary>  
  4. public ProductController()  
  5. {  
  6.     _productServices =new ProductServices();  
  7. }  

Just add a parameter to your constructor that takes your ProductServices reference, as we did in the following:

  1. /// <summary>  
  2. /// Public constructor to initialize product service instance  
  3. /// </summary>  
  4. public ProductController(IProductServices productServices)  
  5. {  
  6.     _productServices = productServices;  
  7. }  

And initialize your “productServices” variable with the parameter. In this case, when the constructor of the controller is called, it will be served with a pre-instantiated service instance and does not need to create an instance of the service, our Unity container did the job of object creation.

Setup Services

For services too, we proceed in a similar fashion. Just open your ProductServices class, we see the dependency of UnitOfWork here as in the following:

  1. /// <summary>  
  2. /// Public constructor.  
  3. /// </summary>  
  4. public ProductServices()  
  5. {  
  6.     _unitOfWork = new UnitOfWork();  
  7. }  

Again, we perform the same steps and a parameter of type UnitOfWork to our constructor.

Our code becomes:

 

  1. /// <summary>  
  2. /// Public constructor.  
  3. /// </summary>  
  4. public ProductServices(UnitOfWork unitOfWork)  
  5. {  
  6.     _unitOfWork = unitOfWork;  
  7. }  

Here we'll also get the pre-instantiated object on UnitOfWork. So the service does not need to worry about creating objects. Remember, we did .RegisterType<UnitOfWork>() in the Bootstrapper class.

We have now made our components independent.

Image source: http://4.bp.blogspot.com/-q-o5SXbf3jw/T0ZUv0vDafI/AAAAAAAAAY4/_O8PgPNXIKQ/s320/h1.jpg

Running the application

Our job is nearly done. We need to run the application. Just hit F5. To our surprise we'll end up with in an error page as in the following:

Do you remember? We added a test client to our project to test our API in my first article. That test client has a controller too, we need to override its settings to make our application work. Just go to Areas -> HelpPage -> Controllers -> HelpController in the WebAPI project as in the following:

Comment out the existing constructors and add a Configuration property like shown below.

  1. //Remove constructors and existing Configuration property.  
  2.   
  3. //public HelpController()  
  4. //    : this(GlobalConfiguration.Configuration)  
  5. //{  
  6. //}  
  7.   
  8. //public HelpController(HttpConfiguration config)  
  9. //{  
  10. //    Configuration = config;  
  11. //}  
  12.   
  13. //public HttpConfiguration Configuration { get; private set; }  
  14.   
  15. /// <summary>  
  16. /// Add new Configuration Property  
  17. /// </summary>  
  18. protected static HttpConfiguration Configuration  
  19. {  
  20.     get { return GlobalConfiguration.Configuration; }  
  21. }  

Our controller code becomes:

  1. using System;  
  2. using System.Web.Http;  
  3. using System.Web.Mvc;  
  4. using WebApi.Areas.HelpPage.Models;  
  5.   
  6. namespace WebApi.Areas.HelpPage.Controllers  
  7. {  
  8.     /// <summary>  
  9.     /// The controller that will handle requests for the help page.  
  10.     /// </summary>  
  11.     public class HelpController : Controller  
  12.     {  
  13.         //Remove constructors and existing Configuration property.  
  14.   
  15.         //public HelpController()  
  16.         //    : this(GlobalConfiguration.Configuration)  
  17.         //{  
  18.         //}  
  19.   
  20.         //public HelpController(HttpConfiguration config)  
  21.         //{  
  22.         //    Configuration = config;  
  23.         //}  
  24.   
  25.         //public HttpConfiguration Configuration { get; private set; }  
  26.   
  27.         /// <summary>  
  28.         /// Add new Configuration Property  
  29.         /// </summary>  
  30.         protected static HttpConfiguration Configuration  
  31.         {  
  32.             get { return GlobalConfiguration.Configuration; }  
  33.         }  
  34.   
  35.         public ActionResult Index()  
  36.         {  
  37.             return View(Configuration.Services.GetApiExplorer().ApiDescriptions);  
  38.         }  
  39.   
  40.         public ActionResult Api(string apiId)  
  41.         {  
  42.             if (!String.IsNullOrEmpty(apiId))  
  43.             {  
  44.                 HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);  
  45.                 if (apiModel != null)  
  46.                 {  
  47.                     return View(apiModel);  
  48.                 }  
  49.             }  
  50.   
  51.             return View("Error");  
  52.         }  
  53.     }  
  54. }  

Just run the application, we get:

We already have our test client added, but for new readers, I am just again explaining how to add a test client to our API project.

Just go to Manage Nuget Packages by right-clicking the WebAPI project and type WebAPITestClient into the searchbox in online packages as in the following:

You'll get “A simple Test Client for ASP.NET Web API”, just add it. You'll get a help controller in Areas -> HelpPage like shown below.

I have already provided the database scripts and data in my previous article, you can use that.

Append “/help” in the application URL and you'll get the test client as in the following:

You can test each service by clicking on it.

Service for GetAllProduct:

To create a new product:

In the database, we get a new product as in the following:

Update product:

We get the following in the database:

Delete product:

In the database:

Job done.

Image source: http://codeopinion.com/wp-content/uploads/2015/02/injection.jpg

Design Flaws

What if I say there are still flaws in this design, the design is still not loosely coupled.

Do you remember what we decided when writing our first application?

Our API talks to services and services talk to the DataModel. We'll never allow the DataModel talk to the APIs for security reasons. But did you notice that when we were registering the type in the Bootstrapper class, we also registered the type of UnitOfWork? That means we added the DataModel as a reference to our API project. This is a design problem. We tried to resolve the dependency of a dependency by violating our design and compromising security.

In my next article, we'll overcome this situation, we'll try to resolve the dependency and its dependency without violating our design and compromising security. In fact, we'll make it more secure and loosely coupled.

In my next article we'll make use of Managed Extensibility Framework (MEF) to do that.

Conclusion

We now know how to use Unity container to resolve a dependency and perform Inversion of Control.

But still there are some flaws in this design. In my next article I'll try to make the system stronger. Until then Happy Coding. You can also download the source code from GitHub. Add the required packages, if they are missing in the source code.

Read more:

For more technical articles you can reach out to CodeTeddy

My other series of articles:

 

Up Next
    Ebook Download
    View all
    Learn
    View all