RESTful Day #4: Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs


Download Source Code

Introduction

We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
Let’s revisit the road map that I started on Web API,
 Here is my roadmap for learning RESTful APIs,
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.

Routing

Routing in generic terms for any service, API, website is a kind of pattern defining system that tries to maps all request from the clients and resolves that request by providing some response to that request. In WebAPI we can define routes in WebAPIConfig file, these routes are defined in an internal Route Table. We can define multiple sets of Routes in that table.

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,
In our existing application, we created WebAPI with default routes as mentioned in the file named WebApiConfig in App_Start folder of WebApi project. The routes were mentioned in the Register method as,
config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
Do not get confused by MVC routes, since we are using MVC project we also get MVC routes defined inRouteConfig.cs file as,
public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
We need to focus on the first one i.e. WebAPI route. As you can see in the following image, what each property signifies,
We have a route name, we have a common URL pattern for all routes, and option to provide optional parameters as well.
Since our application do not have particular different action names, and we were using HTTP VERBS as action names, we didn’t bother much about routes. Our Action names were like,
1. public HttpResponseMessage Get()
2. public HttpResponseMessage Get(int id)
3. public int Post([FromBody] ProductEntity productEntity)
4. public bool Put(int id, [FromBody]ProductEntity productEntity)
5. public bool Delete(int id)

Default route defined does not takes HTTP VERBS action names into consideration and treat them default actions, therefore it does not mentions {action} in routeTemplate. But that’s not limitation, we can have our own routes defined in WebApiConfig, for example, check out the following routes,

  public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
               name: "ActionBased",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
            config.Routes.MapHttpRoute(
              name: "ActionBased",
              routeTemplate: "api/{controller}/action/{action}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
        }
And etc. In above mentioned routes, we can have action names as well, if we have custom actions.
So there is no limit to define routes in WebAPI. But there are few limitations to this, note we are talking about WebAPI 1 that we use with .NET Framework 4.0 in Visual Studio 2010. Web API 2 has overcome those limitations by including the solution that I’ll explain in this article. Let’s check out the limitations of these routes,
Yes, these are the limitations that I am talking about in Web API 1.
If we have route template like routeTemplate: “api/{controller}/{id}” or routeTemplate: “api/{controller}/{action}/{id}” or routeTemplate: “api/{controller}/action/{action}/{id}“,
We can never have custom routes and will have to slick to old route convention provided by MVC. Suppose your client of the project wants to expose multiple endpoints for the service, he can’t do so. We also can not have our own defined names for the routes, so lots of limitation.
Let’s suppose we want to have following kind of routes for my web API endpoints, where I can define versions too,
v1/Products/Product/allproducts
v1/Products/Product/productid/1
v1/Products/Product/particularproduct/4
v1/Products/Product/myproduct/
v1/Products/Product/create
v1/Products/Product/update/3
and so on, then we cannot achieve this with existing model.
Fortunately these things have been taken care of in WebAPI 2 with MVC 5, but for this situation we have AttributeRouting to resolve and overcome these limitations.

Attribute Routing

Attribute Routing is all about creating custom routes at controller level, action level. We can have multiple routes using Attribute Routing. We can have versions of routes as well, in short we have the solution for our exiting problems. Let’s straight away jump on how we can implement this in our exising project. I am not explaining on how to create a WebAPI, for that you can refer my first post of the series.
Step 1: Open the solution ,and open Package Manage Console like shown below in the figure,
Goto Tools->Library Packet manage-> Packet Manager Console
 
Step 2: In the package manager console window at left corner of Visual Studio type, Install-Package AttributeRouting.WebApi, and choose the project WebApi or your own API project if you are using any other code sample, then press enter.
 
Step 3: As soon as the package is installed, you’ll get a class named AttributeRoutingHttpConfig.cs in yourApp_Start folder.
This class has its own method to RegisterRoutes, which internally maps attribute routes. It has a start method that picks Routes defined from GlobalConfiguration and calls the RegisterRoutes method,
using System.Web.Http;
using AttributeRouting.Web.Http.WebHost;

[assembly: WebActivator.PreApplicationStartMethod(typeof(WebApi.AttributeRoutingHttpConfig), "Start")]

namespace WebApi 
{
    public static class AttributeRoutingHttpConfig
 {
  public static void RegisterRoutes(HttpRouteCollection routes) 
  {    
   // See http://github.com/mccalltd/AttributeRouting/wiki for more options.
   // To debug routes locally using the built in ASP.NET development server, go to /routes.axd

            routes.MapHttpAttributeRoutes();
  }

        public static void Start() 
  {
            RegisterRoutes(GlobalConfiguration.Configuration.Routes);
        }
    }
}
We don’t even have to touch this class, our custom routes will automatically be taken care of using this class.We just need to focus on defining routes. No coding :-).  You can now use route specific stuff like route names, verbs, constraints, optional parameters, default parameters, methods, route areas, area mappings, route prefixes, route conventions etc.

Setup REST endpoint / WebAPI project to define Routes

Our 90% of the job is done.
We now need to setup or WebAPI project and define our routes.
Our existing ProductController class looks something like shown below,
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;

namespace WebApi.Controllers
{
    public class ProductController : ApiController
    {

        private readonly IProductServices _productServices;

        #region Public Constructor

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

        #endregion

        // GET api/product
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

        // GET api/product/5
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

        // POST api/product
        public int Post([FromBody] ProductEntity productEntity)
        {
            return _productServices.CreateProduct(productEntity);
        }

        // PUT api/product/5
        public bool Put(int id, [FromBody] ProductEntity productEntity)
        {
            if (id > 0)
            {
                return _productServices.UpdateProduct(id, productEntity);
            }
            return false;
        }

        // DELETE api/product/5
        public bool Delete(int id)
        {
            if (id > 0)
                return _productServices.DeleteProduct(id);
            return false;
        }
    }
}
Where we have a controller name Product and Action names as Verbs. When we run the application, we get following type of endpoints only (please ignore port and localhost setting. It’s because I run this application from my local environment),
Get All Products:
Get product By Id:
Create product :
Update product:
Delete product:
Step 1: Add two namespaces to your controller,
using AttributeRouting;
using AttributeRouting.Web.Http;
 

Step 2: Decorate your action with different routes,

Like in above image, I defined a route with name productid which taked id as a parameter. We also have to provide verb (GET, POST, PUT, DELETE, PATCH) along with the route like shown in image. So it is[GET("productid/{id?}")]. You can define whatever route you want for your Action like[GET("product/id/{id?}")], [GET("myproduct/id/{id?}")] and many more.
Now when I run the application and navigate to /help page, I get this,
i.e. I got one more route for Getting product by id. When you’ll test this service you’ll get your desired URL something like: http://localhost:55959/Product/productid/3, that sounds like real REST Smile | :)
Similarly decorate your Action with multiple routes like show below,
        // GET api/product/5
        [GET("productid/{id?}")]
        [GET("particularproduct/{id?}")]
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }
Therefore we see, we can have our custom route names and as well as multiple endpoints for a single Action. That’s exciting.Each endpoint will be different but will serve same set of result.
  • {id?} : here ‘?’ means that parameter can be optional.
  • [GET(“myproduct/{id:range(1, 3)}”)], signifies that the product id’s falling in this range will only be shown.

More Routing Constraints

You can leverage numerous Routing Constraints provided by Attribute Routing. I am taking example of some of them,

Range

To get the product within range, we can define the value, on condition that it should exist in database.
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

Regular Expression

You can use it well for text/string parameters more efficiently.
        [GET(@"id/{e:regex(^[0-9]$)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

e.g. [GET(@"text/{e:regex(^[A-Z][a-z][0-9]$)}")]

Optional Parameters and Default Parameters

You can also mark the service parameters as optional in the route. For example you want to fetch an employee detail from the data base with his name,
[GET("employee/name/{firstname}/{lastname?}")]
public string GetEmployeeName(string firstname, string lastname="mittal")
{
   …………….
  ……………….
}
In the above mentioned code, I marked last name as optional by using question mark ‘?’ to fetch the employee detail. It’s my end user wish to provide the last name or not.
So the above endpoint could be accessed through GET verb with urls,
~/employee/name/akhil/mittal
~/employee/name/akhil
If a route parameter defined is marked optional, you must also provide a default value for that method parameter.
In the above example, I marked ‘lastname’ as an optional one and so provided a default value in the method parameter , if user doesn’t send any value, “mittal” will be used.
In .NET 4.5 Visual Studio > 2010 with WebAPI 2, you can define DefaultRoute as an attribute too, just try it by your own. Use attribute [DefaultRoute] to define default route values.
You can try giving custom routes to all your controller actions.
I marked my actions as,
        // GET api/product
        [GET("allproducts")]
        [GET("all")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

        // GET api/product/5
        [GET("productid/{id?}")]
        [GET("particularproduct/{id?}")]
        [GET("myproduct/{id:range(1, 3)}")]
        public HttpResponseMessage Get(int id)
        {
            var product = _productServices.GetProductById(id);
            if (product != null)
                return Request.CreateResponse(HttpStatusCode.OK, product);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

        // POST api/product
        [POST("Create")]
        [POST("Register")]
        public int Post([FromBody] ProductEntity productEntity)
        {
            return _productServices.CreateProduct(productEntity);
        }

        // PUT api/product/5
        [PUT("Update/productid/{id}")]
        [PUT("Modify/productid/{id}")]
        public bool Put(int id, [FromBody] ProductEntity productEntity)
        {
            if (id > 0)
            {
                return _productServices.UpdateProduct(id, productEntity);
            }
            return false;
        }

        // DELETE api/product/5
        [DELETE("remove/productid/{id}")]
        [DELETE("clear/productid/{id}")]
        [PUT("delete/productid/{id}")]
        public bool Delete(int id)
        {
            if (id > 0)
                return _productServices.DeleteProduct(id);
            return false;
        }
And therefore get the routes as,

GET

POST / PUT / DELETE

Check for more constraints here.
You must be seeing “v1/Products” in every route, that is due to RoutePrefix I have used at controller level. Let’s discuss RoutePrefix in detail.

RoutePrefix: Routing at Controller level

We were marking our actions with particular route, but guess what, we can mark our controllers too with certain route names, we can achieve this by using RoutePrefix attribute of AttributeRouting. Our controller was named Product, and I want to append Products/Product before my every action, there fore without duplicating the code at each and every action, I can decorate my Controller class with this name like shown below,
    [RoutePrefix("Products/Product")]
    public class ProductController : ApiController
    {
Now, since our controller is marked with this route, it will append the same to every action too. For e.g. route of following action,
        [GET("allproducts")]
        [GET("all")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }
Now becomes,
~/Products/Product/allproducts
~/Products/Product/all

RoutePrefix: Versioning

Route prefix can also be used for versioning of the endpoints, like in my code I provided “v1” as version in my RoutePrefix as shown below,
    [RoutePrefix("v1/Products/Product")]
    public class ProductController : ApiController
    {
Therefore “v1” will be appended to every route / endpoint of the service. When we release next version, we can certainly maintain a change log separately and mark the endpoint as “v2” at controller level, that will append “v2” to all actions,
e.g.
~/v1/Products/Product/all

~/v2/Products/Product/allproducts
~/v2/Products/Product/all

RoutePrefix: Overriding

This functionality is present in .NET 4.5 with Visual Studio > 2010 with WebAPI 2. You can test it there.
There could be situations that we do not want to use RoutePrefix for each and every action. AttributeRoutingprovides such flexibility too, that despite of RoutePrefix present at controller level, an individual action could have its own route too. It just need to override the default route like shown below,

RoutePrefix at Controller

     [RoutePrefix("v1/Products/Product")]
    public class ProductController : ApiController
    {

Independent Route of Action

       [Route("~/MyRoute/allproducts")]
        public HttpResponseMessage Get()
        {
            var products = _productServices.GetAllProducts();
            var productEntities = products as List ?? products.ToList();
            if (productEntities.Any())
                return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

Disable Default Routes

You must be wondering that in the list of all the URL’s on service help page, we are getting some different/other routes that we have not defined through attribute routing starting like ~/api/Product. These routes are the outcome of default route provided in WebApiConfig file, remember? If you want to get rid of those unwanted routes, just go and comment everything written in Register method in WebApiConfig.cs file under Appi_Startfolder,
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);
You can also remove the complete Register method, but for that you need to remove its calling too fromGlobal.asax file.

Running the application

Just run the application, we get,
We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox 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,

GET

POST

PUT

DELETE

You can test each service by clicking on it. Once you click on the service link, you’ll be redirected to test the service page of that particular service. On that page there is a button Test API in the right bottom corner, just press that button to test your service,
Service for Get All products,
Likewise you can test all the service endpoints.

Conclusion

We now know how to define our custom endpoints and what its benefits are. Just to share that this library was introduced by Tim Call, author of http://attributerouting.net and Microsoft has included this in WebAPI 2 by default. My next article will explain token based authentication using ActionFilters in WepAPI. ’til then Happy Coding Smile | :) you can also download the complete source code from GitHub. Add the required packages, if they are missing in the source code.
Click Github Repository to browse for complete source code.

Download Source Code

References

My other series of articles:

RESTful Day #3: Resolve dependency of dependencies using Inversion of Control and dependency injection in ASP.NET Web APIs with Unity Container and Managed Extensibility Framework (MEF)


Download Source Code

Introduction

In my last two articles, I explained how to create a RESTful service using ASP.NET Web API working with Entity Framework and resolving dependencies using Unity Container. In this article, I’ll explain how to create a loosely coupled system with Unity Container and MEF (Managed Extensibility Framework) using Inversion of Control. I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who are following this series, they can use their existing solution that they have created till time. For my new readers of this article, I have provided the download link for the previous source code and current source code as well.
For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC).

Roadmap

Here is my roadmap for learning RESTful APIs,
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,
We tried to design a loosely coupled architecture in the following way,
  • DataModel (responsible for communication with database) : Only talks to service layer.
  • Services (acts as a business logic layer between REST endpoint and data access) : Communicates between REST endpoint and DataModel.
  • REST API i.e. Controllers: Only talks to services via the interfaces exposed.
But when we tried to resolve the dependency of UnitOfWork from Services, we had to reference
DataModel dll in to our WebAPI project; this violated our system like shown in following image,
In this article we’ll try to resolve dependency (data model) of a dependency (services) from our existing solution. My controller depended on services and my services depended on data model. Now we’ll design an architecture in which components will be independent of each other in terms of object creation and instantiation. To achieve this we’ll make use of MEF(Managed Extensibility Framework) along with Unity Container and reflection.
Ideally, we should not be having the below code in our Bootstrapper class,
container.RegisterType().RegisterType(new HierarchicalLifetimeManager());

Managed Extensibility Framework (MEF)

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

“The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well.”
“MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET.”

Creating a Dependency Resolver with Unity and MEF

Open your Visual studio, I am using VS 2010, you can use VS version 2010 or above. Load the solution.
Step 1: Right click solution explorer and add a new project named Resolver,
I have intentionally chosen this name, and you already know it why J
Step 2: Right click Resolver project and click on ManageNugetPackage, in the interface of adding new package, search Unity.MVC3 in online library,
Install the package to your solution.
Step 3: Right click resolver project and add a reference to System.ComponentModel.Composition.
You can find the dll into your GAC.I am using framework 4.0, so referring to the same version dll.
This DLL is the part of MEF and is already installed with .NET Framework 4.0 in the system GAC. This DLL provides classes that are very core of MEF.
Step 4: Just add an interface named IComponent to Resolver project that contains the initialization method named Setup. We’ll try to implement this interface into our Resolver class that we’ll create in our other projects like DataModel, Services and WebApI.
namespace Resolver
{
    /// <summary>
    /// Register underlying types with unity.
    /// </summary>
    public interface IComponent
    {
      
    }
}
Step 5: Before we declare our Setup method, just add one more interface responsible for serving as a contract to register types. I name this interface as IRegisterComponent,
namespace Resolver
{
    /// <summary>
    /// Responsible for registering types in unity configuration by implementing IComponent
    /// </summary>
    public interface IRegisterComponent
    {
        /// <summary>
        /// Register type method
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <typeparam name="TTo"></typeparam>
        /// <param name="withInterception"></param>
        void RegisterType(bool withInterception = false) where TTo : TFrom;
 
        /// <summary>
        /// Register type with container controlled life time manager
        /// </summary>
        /// <typeparam name="TFrom"></typeparam>
        /// <typeparam name="TTo"></typeparam>
        /// <param name="withInterception"></param>
        void RegisterTypeWithControlledLifeTime(bool withInterception = false) where TTo : TFrom;
    }
}
In this interface I have declared two methods, one RegisterType and other in to RegisterType with Controlled life time of the object, i.e. the life time of an object will be hierarchal in manner. This is kind of same like we do in Unity.
Step 6: Now declare Setup method on our previously created IComponent interface, that takes instance ofIRegisterComponent as a parameter,
void SetUp(IRegisterComponent registerComponent);
So our IComponent interface becomes,
namespace Resolver
{
    /// <summary>
    /// Register underlying types with unity.
    /// </summary>
    public interface IComponent
    {
        void SetUp(IRegisterComponent registerComponent);
    }
}
Step 6: Now we’ll write a packager or you can say a wrapper over MEF and Unity to register types/ components. This is the core MEF implementation. Create a class named ComponentLoader, and add following code to it,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Reflection;
 
namespace Resolver
{
    public static class ComponentLoader
    {
        public static void LoadContainer(IUnityContainer container, string path, string pattern)
        {
            var dirCat = new DirectoryCatalog(path, pattern);
            var importDef = BuildImportDefinition();
            try
            {
                using (var aggregateCatalog = new AggregateCatalog())
                {
                    aggregateCatalog.Catalogs.Add(dirCat);
 
                    using (var componsitionContainer = new CompositionContainer(aggregateCatalog))
                    {
                        IEnumerable exports = componsitionContainer.GetExports(importDef);
 
                        IEnumerable modules =
                            exports.Select(export => export.Value as IComponent).Where(m => m != null);
 
                        var registerComponent = new RegisterComponent(container);
                        foreach (IComponent module in modules)
                        {
                            module.SetUp(registerComponent);
                        }
                    }
                }
            }
            catch (ReflectionTypeLoadException typeLoadException)
            {
                var builder = new StringBuilder();
                foreach (Exception loaderException in typeLoadException.LoaderExceptions)
                {
                    builder.AppendFormat("{0}\n", loaderException.Message);
                }
 
                throw new TypeLoadException(builder.ToString(), typeLoadException);
            }
        }
 
        private static ImportDefinition BuildImportDefinition()
        {
            return new ImportDefinition(
                def => true, typeof(IComponent).FullName, ImportCardinality.ZeroOrMore, false, false);
        }
    }
 
    internal class RegisterComponent : IRegisterComponent
    {
        private readonly IUnityContainer _container;
 
        public RegisterComponent(IUnityContainer container)
        {
            this._container = container;
            //Register interception behaviour if any
        }
 
        public void RegisterType(bool withInterception = false) where TTo : TFrom
        {
            if (withInterception)
            {
                //register with interception
            }
            else
            {
                this._container.RegisterType();
            }
        }
 
        public void RegisterTypeWithControlledLifeTime(bool withInterception = false) where TTo : TFrom
        {
            this._container.RegisterType(new ContainerControlledLifetimeManager());
        }
    }
}
Step 7: Now our Resolver wrapper is ready. Build the project and add its reference to DataModel, BusinessServices and WebApi project like shown below,

Setup Business Services

We already have added reference of Resolver in BusinessServices project. We agreed to implement IComponent interface in each of our project.
So create a class named DependencyResolver and implement IComponent interface into it, we make use of reflection too to import IComponent type. So add a class and add following code to that DependencyResolverclass,
using System.ComponentModel.Composition;
using DataModel;
using DataModel.UnitOfWork;
using Resolver;
 
namespace BusinessServices
{
    [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
 
        }
    }
}
Note that we have implemented SetUp method and in the same method we registered type for my ProductService.
All of the existing code base remains same. We don’t need to touch the IProductServices interface or ProductServices class.

Setup DataModel

We have added Resolver project reference to DataModel project as well. So we’ll try to register the type of UnitOfWork in this project. We proceed in same fashion, just add a DependencyResolver class and implement its Setup method to register type of UnitOfWork. To make the code more readable and standard, I made a change.I just added an interface for UnitOfWork and named it IUnitOfWork. Now my UnitOfWork class derives from this, you can do this exercise in earlier versions of projects we discussed in first two articles.
So my IUnitOfWork contains declaration of a single public method in UnitOfWork,
namespace DataModel.UnitOfWork
{
    public interface IUnitOfWork
    {
        /// <summary>
        /// Save method.
        /// </summary>
        void Save();
    }
}
Now register the type for UnitOfWork in DepenencyResolver class, our class becomes as shown below,
using System.ComponentModel.Composition;
using System.Data.Entity;
using DataModel.UnitOfWork;
using Resolver;
 
namespace DataModel
{
    [Export(typeof(IComponent))]
    public class DependencyResolver : IComponent
    {
        public void SetUp(IRegisterComponent registerComponent)
        {
            registerComponent.RegisterType();
        }
    }
}
Again, no need to touch any existing code of this project.

Setup REST endpoint / WebAPI project

Our 90% of the job is done.
We now need to setup or WebAPI project. We’ll not add any DependencyResolver class in this project. We’ll invert the calling mechanism of layers in Bootstrapper class that we already have, so when you open your bootstrapper class, you’ll get the code something like,
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;
        }
    }
}
Now, we need to change the code base a bit to make our system loosely coupled.Just remove the reference of DataModel from WebAPI project.
We don’t want our DataModel to be exposed to WebAPI project, that was our aim though, so we cut down the dependency of DataModel project now.
Add following code of Bootstrapper class to the existing Bootstarpper class,
using System.Web.Http;
//using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Resolver;
using Unity.Mvc3;
 
namespace WebApi
{
    public static class Bootstrapper
    {
        public static void  Initialise()
        {
            var container = BuildUnityContainer();
 
            System.Web.Mvc.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());
 
            RegisterTypes(container);
 
            return container;
        }
 
        public static void RegisterTypes(IUnityContainer container)
        {
 
            //Component initialization via MEF
            ComponentLoader.LoadContainer(container, ".\\bin", "WebApi.dll");
            ComponentLoader.LoadContainer(container, ".\\bin", "BusinessServices.dll");
 
        }
    }
}
It is kind of redefining Bootstrapper class without touching our existing controller methods. We now don’t even have to register type for ProductServices as well, we already did this in BusinessServices project.
Note that in RegisterTypes method we load components/dlls through reflection making use of ComponentLoader.We wrote two lines, first to load WebAPI.dll and another one to load Business Services.dll.
Had the name of BusinessServicess.dll be WebAPI.Services.dll, then we would have only written one line of code to load both the WebAPI and BusinessService dll like shown below,
ComponentLoader.LoadContainer(container, ".\\bin", "WebApi*.dll");
Yes we can make use of Regex.

Running the application

Just run the application, we get,
We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox 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. Once you click on the service link, you’ll be redirected to test the service page of that particular service. On that page there is a button Test API in the right bottom corner, just press that button to test your service,
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:

Advantages of this design

In my earlier articles I focussed more on design flaws, but our current design have emerged with few added advantages,
  1. We got an extensible and loosely coupled application design that can go far with more new components added in the same way.
  2. Registering types automatically through reflection. Suppose we want to register any Interface implementation to our REST endpoint, we just need to load that dll in our Bootstrapper class, or if dll’s are of common suffix names then we just have to place that DLL in bin folder, and that will automatically be loaded at run time.
  3. Database transactions or any of such module is now not exposed to the service endpoint, this makes our service more secure and maintains the design structure too.

Conclusion

We now know how to use Unity container to resolve dependency and perform inversion of control using MEF too. In my next article I’ll try to explain how we can open multiple endpoints to our REST service and create custom url’s in the true REST fashion in my WebAPI. Till then Happy Coding Smile | :) You can also download the source code from GitHub. Add the required packages, if they are missing in the source code.

Download Source Code