Step by Step Implementing Onion Architecture in ASP.Net MVC Application

This article will help you implement the Onion Architecture in ASP.NET MVC applications.

Source Code on the GitHub

Recently I gave a talk on the Onion Architecture in MVC applications to the audience of 300 at the C-Sharpcorner conference 2015. The talk was well received and I had many requests to write a step-by-step article on it. So here I am writing that. This article is written in the simplest words possible and will help you in implementing the Onion Architecture in ASP.NET MVC applications. Even though the theme of this article is ASP.NET MVC, you can use the core, infrastructure and the test project with other kinds of applications as well like WCF or WPF.

You may want to read: Refactoring the ASP.NET MVC Application to the Onion Architecture

Source Code on the GitHub

What the Onion Architecture is

The Onion Architecture is the preferred way of architecting applications for better testability, maintainability and dependability on the infrastructures like databases and services. This term was first coined by Jeffery Palermo in his blog back in 2008.

Advantages of Onion Architecture
  • In the Onion Architecture layers talk to each other using the interfaces. Any concrete implantation would be provided to the application at run time
  • Any external dependency like database access and the web service call are part of the external layers
  • The UI is part of the external layers
  • Objects representing domains are part of the internal layers or they are the centers
  • External layers can depend on the layers internal to it or central to it
  • The internal layer should not depend on the external layers
  • The domain object that is at the core or centre can have access to both the UI and the database layers
  • All the coupling are towards the centre
  • Code that may change often should be part of the external layers

Project structure

Let us start with creating the solution structure. We will work with the following four projects.

  1. Core project (Class library )
  2. Infrastructure project (Class library)
  3. Test project (Unit Test project)
  4. Web project (MVC project)

The Core project will contain the domain entities and the repositories interfaces. The infrastructure project will contain the classes (in this case EF data context) that will work with the database. The Test project will have the tests and the MVC project will contain the MVC controllers and the view.

The solution structure should look such as listed in the following image.

Core project

The core project is the inner-most layer of the architecture. All the external layers, like infrastructure, web and so on will use and depend on the core layer. However the core project does not depend on any other layers.

Usually the core project should contain:

  1. Domain entities
  2. Repositories interfaces

It should not have any external dependencies. For example we must not have the following references in the core project:

  1. Reference of the ORM like LINQ to SQL or EF
  2. Reference of ADO.NET libraries
  3. Reference of Entity Framework and so on

Create Entity

Let us proceed to creating the BloodDonor entity class.

  1. public class BloodDonor  
  2. {  
  3.     public string BloodDonorID { getset; }  
  4.     public string Name { getset; }  
  5.     public DateTime Dob { getset; }  
  6.     public string BloodGroup { getset; }  
  7.     public string City { getset; }  
  8.     public string Country { getset; }  
  9.     public int PinCode { getset; }  
  10.     public string PhoneNumber { getset; }  
  11.     public string Email { getset; }  
  12.     public bool IsActive { getset; }  
  13.     public bool IsPrivate { getset; }  
  14.     public bool IsVerified { getset; }  
  15. }  
We may have a requirement to have some restrictions on the entity properties. For example, the maximum length, required and so on. We do have the following two choices to do this:
  1. Using System.ComponentModel.DataAnnotations
  2. Use Entity Framework fluent API.

Both of the preceding approaches have their own advantages. However to keep the core project without any external dependencies like EntityFramework, I prefer to use DataAnnotations. To use the DataAnnotations add a System.ComponentModel.DataAnnotations reference to the core project. We can modify the entity class as shown in the listing below:

  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  4. namespace LifeLine.Core  
  5. {  
  6.     public class BloodDonor  
  7.     {  
  8.         [Required]  
  9.         public string BloodDonorID { getset; }  
  10.         [Required]  
  11.         [MaxLength(50)]  
  12.         public string Name { getset; }  
  13.         [Required]  
  14.         public string BloodGroup { getset; }  
  15.         [Required]  
  16.         public string City { getset; }  
  18.         public string Country { getset; }  
  19.         [Required]  
  20.         public int PinCode { getset; }  
  21.         [Required]  
  22.         public string PhoneNumber { getset; }  
  23.         public string Email { getset; }  
  24.         public bool IsActive { getset; }  
  25.         public bool IsPrivate { getset; }  
  26.         public bool IsVerified { getset; }  
  27.     }  
  28. }  
As of now we have created the BloodDonor entity class with the data annotations. Next we need to add the repository interface.

Create Repository interface

We will follow the repository pattern. Roughly, the repository pattern allows us to replace the database access codes (class) without affecting the other layers. In the repository interface we will put the definition of all the database operations to be performed.
  1. using System.Collections.Generic;  
  2. namespace LifeLine.Core.Interfaces  
  3. {  
  4.     public interface IBloodDonorRepository   
  5.     {  
  6.         void Add(BloodDonor b);  
  7.         void Edit(BloodDonor b);  
  8.         void Remove(string BloodDonorID);  
  9.         IEnumerable < BloodDonor > GetBloodDonors();  
  10.         BloodDonor FindById(string BloodDonorID);  
  12.     }  
  13. }  
As of now we have created the domain entity and the repository interface. Next let us proceed to create the infrastructure project.

Infrastructure project

In the infrastructure project we perform operations related to outside the application. For example:
  1. Database operation
  2. Accessing outside service
  3. Accessing File systems

The preceding operations should be part of the infrastructure project. We will use the Entity Framework to do the database operations. We are working with the Entity Framework code first approach, so we need to perform the following procedure:

  1. Create the data context class
  2. Implement the repository class
  3. Create the database initializer class

Before we proceed to create the data context class, let us go ahead and add a reference of the Entity Framework. To add the reference right-click on the infrastructure project and select Manage Nuget Package. From the Nuget Package Manager select the Entity Framework package to install into the project.

DataContext class

Let us create the data context class. In the EF code first approach, we create the data context class that will represent the database. Since we have only one business entity, we will create one table, BloodDonors.

  1. using System.Data.Entity;  
  2. using LifeLine.Core;  
  4. namespace LifeLine.Infrastructure   
  5. {  
  6.     public class BloodDonorContext: DbContext  
  7.     {  
  8.         public BloodDonorContext(): base("name=BloodDonorContextConnectionString")   
  9.         {  
  10.             var a = Database.Connection.ConnectionString;  
  11.         }  
  13.         public DbSet < BloodDonor > BloodDonors{get;set;}  
  14.     }  
  15. }  
Connection string

Optionally, you can either pass the connection string or rely on the Entity Framework to create the database. We will set up the connection string in app.config of the infrastructure project. Let us proceed to set the connection string as shown in the following listing:

  1. < connectionStrings >   
  2. < add name = "BloodDonorContextConnectionString" connectionString = "Data Source= LocalDb)\v11.0;Initial Catalog=BloodDonors;Integrated Security=True;MultipleActiveResultSets=true" providerName = "System.Data.SqlClient" / >   
  3. < /connectionStrings>  
Database initialize class 

We want the database to be initialized with some initial values. It can be done as shown in the following listing:
  1. using System;  
  2. using System.Data.Entity;  
  3. using LifeLine.Core;  
  5. namespace LifeLine.Infrastructure  
  6. {  
  7.     public class BloodDonorInitalizeDb: DropCreateDatabaseIfModelChanges < BloodDonorContext > {  
  9.         protected override void Seed(BloodDonorContext context)   
  10.         {  
  11.             context.BloodDonors.Add(  
  12.             new BloodDonor   
  13.             {  
  14.                 Name = "Rahul Kapoor",  
  15.                 City = "Gurgaon",  
  16.                 BloodGroup = "A+",  
  17.                 BloodDonorID = "BD1",  
  18.                 Country = "India",  
  19.                 IsActive = true,  
  20.                 IsPrivate = false,  
  21.                 IsVerified = true,  
  22.                 PhoneNumber = "91+7378388383",  
  23.                 PinCode = 122002,  
  24.                 Email = ""  
  26.             });  
  27.             context.BloodDonors.Add(  
  28.             new BloodDonor  
  29.             {  
  30.                 Name = "Salman Khan",  
  31.                 City = "Mumbai",  
  32.                 BloodGroup = "A-",  
  33.                 BloodDonorID = "BD2",  
  34.                 Country = "India",  
  35.                 IsActive = true,  
  36.                 IsPrivate = false,  
  37.                 IsVerified = true,  
  38.                 PhoneNumber = "91+84848484",  
  39.                 PinCode = 25678,  
  40.                 Email = ""  
  41.             });  
  42.             base.Seed(context);  
  43.         }  
  44.     }  
  45. }  
We are setting the value that, if the model changes, recreate the database. We can explore the other options of the Entity Framework also.

Repository class implementation

Next we need to implement the repository class. The repository class will access the database using the LINQ to Entity. To create the BloodDonorRepository class let us proceed to create a class that will implement the IBloodDonorRepository interface.
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using LifeLine.Core;  
  4. using LifeLine.Core.Interfaces;  
  6. namespace LifeLine.Infrastructure  
  7. {  
  8.     public class BloodDonorRepository: IBloodDonorRepository {  
  9.         BloodDonorContext context = new BloodDonorContext();  
  10.         public void Add(BloodDonor b)   
  11.         {  
  12.             context.BloodDonors.Add(b);  
  13.             context.SaveChanges();  
  14.         }  
  16.         public void Edit(BloodDonor b)   
  17.         {  
  18.             context.Entry(b).State = System.Data.Entity.EntityState.Modified;  
  19.         }  
  21.         public void Remove(string BloodDonorID)   
  22.         {  
  23.             BloodDonor b = context.BloodDonors.Find(BloodDonorID);  
  24.             context.BloodDonors.Remove(b);  
  25.             context.SaveChanges();  
  26.         }  
  28.         public IEnumerable < BloodDonor > GetBloodDonors()   
  29.         {  
  30.             return context.BloodDonors;  
  31.         }  
  33.         public BloodDonor FindById(string BloodDonorID)   
  34.         {  
  35.             var bloodDonor = (from r in context.BloodDonors where r.BloodDonorID == BloodDonorID select r).FirstOrDefault();  
  36.             return bloodDonor;  
  37.         }  
  38.     }  
  39. }  
To implement the repository class, we are using the LINQ to Entity for the database operations. For example to add a blood donor:
  1. Create object of context class
  2. Use context.entiy.Add(entity)
  3. Use context.SaveChnages()

As of now we have implemented the infrastructure project. Be sure to build the project to confirm everything is fine.

Whether to directly do something to the MVC project or write a test

After creation of core project and the infrastructure project, we need to take a decision that whether we want to directly create the MVC project or write the unit test for the repository class. Better approach would be to write the Unit tests for the repository class such that we would be sure that database related code has been implemented correctly.

Test Project

We have created a test project by selecting the Unit Test project template from the Test project tab. To start writing the test, very first in the unit test project we need to add the following references:

  1. Reference of the core project
  2. Reference of the infrastructure project
  3. Entity Framework package
  4. Reference of the System.LINQ

In the test project, I have created a class called BloodDonorRepositoryTest. Inside the unit test class initialize the test as shown in the listing below:

  1. BloodDonorRepository repo;  
  2. [TestInitialize]  
  3. public void TestSetUp()   
  4. {  
  6.     BloodDonorInitalizeDb db = new BloodDonorInitalizeDb();  
  7.     System.Data.Entity.Database.SetInitializer(db);  
  8.     repo = new BloodDonorRepository();  
  9. }  
In the test setup, we are creating an instance of the BloodDonorInitalizeDb class and then setting up the database with the initial values. Also in the test setup, an instance of the repository class is created. Next let us create a test to validate whether or not the database is initialized with the right number of data.
  1. [TestMethod]  
  2. public void IsRepositoryInitalizeWithValidNumberOfData()   
  3. {  
  4.     var result = repo.GetBloodDonors();  
  5.     Assert.IsNotNull(result);  
  6.     var numberOfRecords = result.ToList().Count;  
  7.     Assert.AreEqual(2, numberOfRecords);  
  8. }  
In the test above we are calling the GetBloodDonors method of the repository class and then verifying the number of records. In an ideal condition the preceding test should be passed. You can verify the test results in the Test-Window-Test Explorer.

We can create tests for add, edit and delete also. As of now we have written a test to verify that the database is being created along with the initialized data. We can be sure about the implementation of the repository class after passing the test. Now let us proceed to implement the web project.

Web Project

We will create a MVC project that will use the core project and the infrastructure project. Add the following reference to the MVC project:
  1. Reference of infrastructure project
  2. Reference of core project
  3. Entity Framework package

After adding all the references, build the web project. If everything is fine then we should get a successful build. Next let us right-click on the Controller folder and add a new controller. Select create controller with Entity Framework with view option. Provide the name of the controller as BloodDonorsController.

Also we need to select the following options:

  1. BloodDonor class from the core project as the Model class
  2. BloodDonorContext class as the data context class from the Infrastructure project

We have created the controller along with the view using the scaffolding. At this point if we notice the web project, we will find the BloodDonors controller and a BloodControllers subfolder in the view folder.

As of now we have created the controller using the model and data context class. Next we need to create an instance of the BloodDonorInitalizeDb class and set the database. We need to write this code inside the global.asax.

  1. BloodDonorInitalizeDb db = new BloodDonorInitalizeDb();  
  2. System.Data.Entity.Database.SetInitializer(db);  
Last we need to copy the connection string from the app.config of infrastructure project to web.config of the web project. So let us go ahead and copy the connection string in the web.config
  1. <connectionStrings>  
  2. <add name="BloodDonorContextConnectionString" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=BloodDonors;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
At this point if we run the application we should be able to perform the CRUD operations.

Dependency Injection using Unity

We have a running application but there is a problem. On noticing the controller class closely, we will find that the object of the data context class is directly created inside the controller. We used scaffolding to create the controller using the Entity Framework and it causes the creation of a data context object inside the controller. Right now the controller and the data context class are tightly coupled to each other and if we change the database access program then the controller will be affected also. We should not have the BloodDonorContext object inside the controller.

We have already created the repository class inside the infrastructure project. We should use the repository class inside the controller class. We have the following two options to use the repository class.

  1. Directly create the object of the repository class in the controller class
  2. Use dependency injection to resolve the repository interface to the concrete repository class object at run time using the Unity container.

We will use the second approach. To use the Unity container add the Unity.Mvc5 package to the web project using Manage Nuget Package.

After installing the Unity package, we need to register the type. To register the type open the UnityConfig class inside the App_Start folder. As highlighted in the following image, add the register.

And inside the global.asax register all the components of the UnityConfig as shown in the following image.

So far we have added the Unity container reference and registered the type. Now let us proceed to refactor the controller class to use the repository class. To start with:

  1. Create a global variable of the type IBloodDonorRepository
  2. Create controller class constructor with a parameter as shown in the following image:

Once this is done we need to refactor the controller class to use functions of the repository class instead of the data context class. For example, the Index method can be refactored as shown below.

After refactoring, the BloodDonorController class will look such as shown in the following listing:

  1. using System.Linq;  
  2. using System.Net;  
  3. using System.Web.Mvc;  
  4. using LifeLine.Core;  
  5. using LifeLine.Core.Interfaces;  
  6. namespace LifeLine.Web.Controllers   
  7. {  
  8.     public class BloodDonorsController: Controller   
  9.     {  
  10.         IBloodDonorRepository db;  
  12.         public BloodDonorsController(IBloodDonorRepository db)   
  13.         {  
  14.             this.db = db;  
  15.         }  
  17.         // GET: BloodDonors  
  18.         public ActionResult Index()   
  19.         {  
  20.             return View(db.GetBloodDonors().ToList());  
  21.         }  
  23.         // GET: BloodDonors/Details/5  
  24.         public ActionResult Details(string id)   
  25.         {  
  26.             if (id == null)  
  27.             {  
  28.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  29.             }  
  30.             BloodDonor bloodDonor = db.FindById(id);  
  31.             if (bloodDonor == null)   
  32.             {  
  33.                 return HttpNotFound();  
  34.             }  
  35.             return View(bloodDonor);  
  36.         }  
  38.         // GET: BloodDonors/Create  
  39.         public ActionResult Create()   
  40.         {  
  41.             return View();  
  42.         }  
  44.         // POST: BloodDonors/Create  
  45.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  46.         // more details see  
  47.         [HttpPost]  
  48.         [ValidateAntiForgeryToken]  
  49.         public ActionResult Create([Bind(Include = "BloodDonorID,Name,BloodGroup,City,Country,PinCode,PhoneNumber,Email,IsActive,IsPrivate,IsVerified")] BloodDonor bloodDonor)   
  50.         {  
  51.             if (ModelState.IsValid)  
  52.             {  
  53.                 db.Add(bloodDonor);  
  54.                 return RedirectToAction("Index");  
  55.             }  
  57.             return View(bloodDonor);  
  58.         }  
  60.         // GET: BloodDonors/Edit/5  
  61.         public ActionResult Edit(string id)   
  62.         {  
  63.             if (id == null)   
  64.             {  
  65.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  66.             }  
  67.             BloodDonor bloodDonor = db.FindById(id);  
  68.             if (bloodDonor == null)   
  69.             {  
  70.                 return HttpNotFound();  
  71.             }  
  72.             return View(bloodDonor);  
  73.         }  
  75.         // POST: BloodDonors/Edit/5  
  76.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  77.         // more details see  
  78.         [HttpPost]  
  79.         [ValidateAntiForgeryToken]  
  80.         public ActionResult Edit([Bind(Include = "BloodDonorID,Name,BloodGroup,City,Country,PinCode,PhoneNumber,Email,IsActive,IsPrivate,IsVerified")] BloodDonor bloodDonor)   
  81.         {  
  82.             if (ModelState.IsValid)   
  83.             {  
  84.                 db.Edit(bloodDonor);  
  85.                 return RedirectToAction("Index");  
  86.             }  
  87.             return View(bloodDonor);  
  88.         }  
  90.         // GET: BloodDonors/Delete/5  
  91.         public ActionResult Delete(string id)   
  92.         {  
  93.             if (id == null)  
  94.             {  
  95.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  96.             }  
  97.             BloodDonor bloodDonor = db.FindById(id);  
  98.             if (bloodDonor == null)   
  99.             {  
  100.                 return HttpNotFound();  
  101.             }  
  102.             return View(bloodDonor);  
  103.         }  
  105.         // POST: BloodDonors/Delete/5  
  106.         [HttpPost, ActionName("Delete")]  
  107.         [ValidateAntiForgeryToken]  
  108.         public ActionResult DeleteConfirmed(string id)  
  109.         {  
  110.             BloodDonor bloodDonor = db.FindById(id);  
  111.             db.Remove(bloodDonor.BloodDonorID);  
  112.             return RedirectToAction("Index");  
  113.         }  
  114.     }  
  115. }  

This is it. This is the procedure we need to follow to create a MVC application following the Onion Architecture.

Source Code on the GitHub

Have something to add? Please add in the comments section.