Download Source Code
Introduction
Roadmap

- RESTful Day #1: Enterprise level application architecture with Web APIs using Entity Framework, Generic Repository pattern and Unit of Work.
- RESTful Day #2: Inversion of control using dependency injection in Web APIs using Unity Container and Bootstrapper.
- 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).
- RESTful Day #4: Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs.
- RESTful Day #5: Basic Authentication and Token based custom Authorization in Web APIs using Action Filters.
- RESTful Day #6: Request logging and Exception handing/logging in Web APIs using Action Filters, Exception Filters and NLog.
- RESTful Day #7: Unit Testing and Integration Testing in WebAPI using NUnit and Moq framework (Part1).
- RESTful Day #8: Unit Testing and Integration Testing in WebAPI using NUnit and Moq framework (Part 2).
- RESTful Day #9: Extending OData support in ASP.NET Web APIs.
Existing Design and Problem

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


container.RegisterType().RegisterType(new HierarchicalLifetimeManager());
Managed Extensibility Framework (MEF)
“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


System.ComponentModel.Composition
.
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 { } }
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; } }
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.Setup
method on our previously created IComponent interface, that takes instance ofIRegisterComponent
as a parameter,void SetUp(IRegisterComponent registerComponent);
namespace Resolver { /// <summary> /// Register underlying types with unity. /// </summary> public interface IComponent { void SetUp(IRegisterComponent registerComponent); } }
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()); } } }
Resolver
wrapper is ready. Build the project and add its reference to DataModel, BusinessServices and WebApi project like shown below,
Setup Business Services
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 DependencyResolver
class,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(); } } }

SetUp
method and in the same method we registered type for my ProductService.Setup DataModel
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.IUnitOfWork
contains declaration of a single public method in UnitOfWork
,namespace DataModel.UnitOfWork { public interface IUnitOfWork { /// <summary> /// Save method. /// </summary> void Save(); } }
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(); } } }

Setup REST endpoint / 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; } } }

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"); } } }

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.ComponentLoader.LoadContainer(container, ".\\bin", "WebApi*.dll");
Running the application












Advantages of this design
- We got an extensible and loosely coupled application design that can go far with more new components added in the same way.
- 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.
- 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 You can also download the source code from GitHub. Add the required packages, if they are missing in the source code.
Read more:
- C# and ASP.NET Questions (All in one)
- MVC Interview Questions
- C# and ASP.NET Interview Questions and Answers
- Web Services and Windows Services Interview Questions
Other Series
My other series of articles:
For more technical articles you can reach out to CodeTeddy.