Click here to Skip to main content
15,791,673 members
Articles / Security

N - tier project with WCF OData service, Entity Framework, MVC3.0, Ninject DI, and Automapper

Rate me:
Please Sign up or sign in to vote.
4.62/5 (5 votes)
10 Dec 2012CPOL3 min read 38.9K   1.9K   41   5
N-Tier application with WCF Odata service and Entity Framework.

Brief Introduction

This article try to explain unit testable, Decoupled, deployment flexible n-tier architecture. This architecture will also explain Repository pattern in MVC 3.0. It also describe how to inject dependencies using Ninject DI container, How to bind ViewModels to Model using Auto mapper, and create mobile ready site using CSS3.0 media queries.

Using the code

The project has been is created in Visual Studio 2010 with MVC 3.0 with Entity Framework 4.1 and I have also used third party libraries like AutoMapper,, and Ninject.

Before you continue with this sample project you need to follow the below steps.

Install the Northwind database in SQL server (in my case I am using SQL Server Express 2008 R2) you can install the Northwind database in older versions also. Install the Ninject DI Container using this command( Install-Package Ninject) in Nuget package manager console. Install the AutoMapper using this command (Install-Package AutoMapper -Pre ) in Nuget package manager console. Modify the NorthwindEntities database connection string in Web.config file in eShopping UI project. If you have done every thing correctly just run the project.

Architecture of this project

There are five layers in this project 

  1. eShopping.eShoppingDB Persistent layer
  2. eShopping.Business Domain Layer or business layer
  3. Business entities layer 
  4. eShopping UI layer 
  5. AuthenticationProvider  

Image 1

AuthenticationProvider (AuthenticationProvider)

I have added the BasicAuthenticationProvider class to simulate the Authentication functionality, and following method return the true if user authenticated successfully, and set the current user to IPrincipal in current http context.

public static bool Authenticate(HttpContext context)
    if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
        return false;

    string authHeader = HttpContext.Current.Request.Headers["Authorization"];

    IPrincipal principal;
    if (TryGetPrincipal(authHeader, out principal))
        HttpContext.Current.User = principal;
        return true;
    return false;
private static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
    var creds = ParseAuthHeader(authHeader);
    if (creds != null && TryGetPrincipal(creds, out principal))
        return true;

    principal = null;
    return false;

Business Layer(eShopping.Business)

I am accessing WCF OData service using Data Service Context class and DbSContext is the instance of DataServiceContext class. DbSContext will always send the encrypted authorization header when sending request to WCF OData services to get the data. I have used to RijndaelManaged algorithm to encrypt the authorization header.

public static DataServiceContext DbSContext; static GlobalObjects()
     DbSContext = new DataServiceContext(CommonVariables.DbServiceUrl);       
    DbSContext.SendingRequest += newEventHandler<sendingrequesteventargs>(OnSendingRequest);       

internal static void OnSendingRequest(object sender, SendingRequestEventArgs e)
    var creds = Encryption.EncryptString("Administrator") + 
    var bcreds =Encoding.ASCII.GetBytes(creds); 
    var base64Creds = Convert.ToBase64String(bcreds);        
    e.RequestHeaders.Add("Authorization","Basic " + base64Creds); 

WCF OData Service (eShopping.DataService)

I have created a IHttp Module (BasicAuthenticationModule) to authenticate the OData requests from business layer, if user and password do not match, the service will return Unauthorized 404 error message.

I have register this module (BasicAuthenticationModule) in the web.config file

 <add name="BasicAuthenticationModule" 

When WCF OData service receive the request and then application calls the registered module to authenticate the request. 

public void Init(HttpApplication context)
    context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);

void context_AuthenticateRequest(object sender, EventArgs e)      
     HttpApplication application = (HttpApplication)sender; 
       application.Context.Response.Status = "401Unauthorized";
       application.Context.Response.StatusCode = 401;

Business entities layer (eShopping.Entities)

I have placed the entities in one place to maintain the consistency and to remove duplicity. This will help in sharing the same entities in multiple projects like in Database layer, Business layer and UI layer.

UI layer (eShopping)

I have used the Ninjected DI as default Dependency injector, and Automapper to map the Models using view models. 

I have registered the AutoMapper in Global.asax file.

protected void Application_Start()
    ControllerBuilder.Current.SetControllerFactory(new eShoppingControllerFactory());
private void InitializeAutoMapper()


The project is solely based on my self study, knowledge and research, not based on any other project. I have used the term like eShopping but its totally demo term and does not relate to any practically working project. I have used the Microsoft Northwind database which is publically available sample database from Microsoft. I have not implemented a feature for eShopping like shopping, viewing products as they should be, my motive is only to describe n-tier architecture, and most commonly used open source tool with ASP.NET MVC3.0, like Ninject and AutoMapper. I have not added the unit test in this project, so if you want you can add unit test to this project. Please feel free to contact me to add some more functionality to this.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior) Nagarro Softwares
India India
I am vijay tanwar and i am a software engineer with passion of programming. I love to programming in c#, I love to warp up more and more things in few lines of code. my favirote languages are c# and javascript and both are fully object oriended. I always like to become the .net Architect.

Comments and Discussions

QuestionWhat would be the architecture diagram if we have a windows UI too? Pin
alborz moghadam29-Oct-13 4:13
alborz moghadam29-Oct-13 4:13 
GeneralMy vote of 5 Pin
gillindsay17-Dec-12 8:06
professionalgillindsay17-Dec-12 8:06 
Vijay I congratulate you on a decent design. I would consider this a good beginners article to understand how to think about Test-driven design. Using Automapper, nInject, and oData teaches about available design choices. N ote these are not offered as best practices, just good initial design choices.
GeneralMy vote of 2 Pin
Robin Kumar10-Dec-12 20:16
Robin Kumar10-Dec-12 20:16 
SuggestionMissing source code Pin
Smitha Nishant10-Dec-12 5:38
protectorSmitha Nishant10-Dec-12 5:38 
GeneralRe: Missing source code Pin
Vijay Tanwar10-Dec-12 6:34
Vijay Tanwar10-Dec-12 6:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.