Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

RESTful Day #2: Inversion of Control

DZone's Guide to

RESTful Day #2: Inversion of Control

Part two of this series shows how to make an ASP.NET Web API service architecture loosely coupled and more flexible using dependency injection in Web APIs and Unity Container and Bootstrapper.

· Integration Zone
Free Resource

Discover how Microservices are a type of software architecture where large applications are made up of small, self-contained units working together through APIs that are not dependent on a specific language. Brought to you in partnership with AppDynamics.

This article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learned that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in 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 to a test application from my first article.

Image title

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

There are various methods you can use to resolve dependency of components. In my article, I’ll explain how to resolve dependency with the help of 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 follow the following links: Unity and Inversion of Control(IOC). We’ll straight away jump into practical implementation.

Roadmap

I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can 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 mentioned 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:

Controller constructor makes an object of Service layer to communicate,

        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }

Service constructor, in turn, makes an object of UnitOfWork to communicate to database,

        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

The problem lies in these code pieces. We see Controller is dependent upon instantiation of Service and Service is dependent upon UnitOfWork to get instantiated. Our Layers should not be that tightly coupled and should be dependent on each other.

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

We’ll assign this role to a third party that will be called our container. Fortunately, Unity provides that help to us, to get rid of this dependency problem and invert the control flow by injecting dependency not by creating objects by new but through 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, which 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.”

Set up Unity

Open your Visual studio, I am using VS 2010, You can use VS version 2010 or above. Load the solution.

Step 1: browse to Tools-> Library Packet Manager – > Packet manager Console,








We’ll add package for Unity Application Block.

In the left bottom 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: Bootstrapper class

Unity.MVC3 comes with a Bootstrapper class, as soon as you run the command, the Bootstrapper class will be generated in your solution->WebAPI project,

using System.Web.Http;
using System.Web.Mvc;
using BusinessServices;
using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Unity.Mvc3;

namespace WebApi
{
    public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType();        
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

            return container;
        }
    }
}











This class comes with an initial configuration to setup your container. All the functionality is inbuilt, we only need to specify the dependencies that we need to resolve in the “BuildUnityContainer“, like it says in the commented statement,

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType();

Step 3: Just specify the components below these commented lines that we need to resolve. In our case, it’sProductServices and UnitOfWork, so just add,

container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

HierarchicalLifetimeManager” maintains the lifetime of the object, and the child object depends upon the parent object’s lifetime.

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

So our Bootstrapper class becomes,

   public static class Bootstrapper
    {
        public static void Initialise()
        {
            var container = BuildUnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            // register dependency resolver for WebAPI RC
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        }

        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType();        
            container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

            return container;
        }

Like this, we can also specify other dependent objects in BuildUnityContainerMethod.

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

Bootstrapper.Initialise();

Our global.asax becomes,

using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using WebApi.App_Start;

namespace WebApi
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //Initialise Bootstrapper
            Bootstrapper.Initialise();

            //Define Formatters
            var formatters = GlobalConfiguration.Configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.Indented;
            // settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            var appXmlType = formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            //Add CORS Handler
            GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
        }
    }
}

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.

Set up Controller

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

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

        /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }

Just add a parameter to your constructor that takes your ProductServices reference, like we did below

       /// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController(IProductServices productServices)
        {
            _productServices = productServices;
        }

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

Set up Services

For services we proceed in the same fashion. Just open your ProductServices class, we see the dependency of UnitOfWork here as,

        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

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

Our code becomes,

        /// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

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

We have now made our components independent.





Image source: https://codeteddycom.files.wordpress.com/2015/05/d91c4-h1.jpg

Running the Application

Our job is almost done.We need to run the application, Just hit F5. To our surprise we’ll end up in an error page,











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 WebAPI project like shown below,











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

      //Remove constructors and existing Configuration property.

        //public HelpController()
        //    : this(GlobalConfiguration.Configuration)
        //{
        //}

        //public HelpController(HttpConfiguration config)
        //{
        //    Configuration = config;
        //}

        //public HttpConfiguration Configuration { get; private set; }

        /// <summary>
        /// Add new Configuration Property
        /// </summary>
        protected static HttpConfiguration Configuration
        {
            get { return GlobalConfiguration.Configuration; }
        }

Our controller code becomes,

using System;
using System.Web.Http;
using System.Web.Mvc;
using WebApi.Areas.HelpPage.Models;

namespace WebApi.Areas.HelpPage.Controllers
{
    /// <summary>
    /// The controller that will handle requests for the help page.
    /// </summary>
    public class HelpController : Controller
    {
        //Remove constructors and existing Configuration property.

        //public HelpController()
        //    : this(GlobalConfiguration.Configuration)
        //{
        //}

        //public HelpController(HttpConfiguration config)
        //{
        //    Configuration = config;
        //}

        //public HttpConfiguration Configuration { get; private set; }

        /// <summary>
        /// Add new Configuration Property
        /// </summary>
        protected static HttpConfiguration Configuration
        {
            get { return GlobalConfiguration.Configuration; }
        }

        public ActionResult Index()
        {
            return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
        }

        public ActionResult Api(string apiId)
        {
            if (!String.IsNullOrEmpty(apiId))
            {
                HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
                if (apiModel != null)
                {
                    return View(apiModel);
                }
            }

            return View("Error");
        }
    }
}

Just run the application, we get,









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

Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in the search box in online packages,










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 the same.

Append “/help” in the application URL, and you’ll get the test client,










You can test each service by clicking on it.

Service for GetAllProduct,










For creating a new product,








In the database, we get a new product,









Update product:









We get in the database,







Delete product:








In 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 while writing our first application?

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

Discover the six challenges and best practices in managing microservice performance, brought to you in partnership with AppDynamics.

Topics:
webapi ,rest api ,asp.net ,mvc framework ,c#

Published at DZone with permission of Akhil Mittal. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}