2015-04-17



alvinashcraft
shared this story
from Dhananjay Kumar.

Source Code on the GitHub

Recently I gave a talk on Onion Architecture in MVC application to the audience of 300 at the C-Sharpcorner conference 2015. Talk was well received and I had a many request to write a step by step blog post on the same. So here I am writing that. In this blog post is written in simplest words and will help you in implementing onion architecture in ASP.NET MVC application. Even though theme of this post is ASP.NET MVC, you can use the core, infrastructure and the test project with other kind 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 is onion architecture

Onion Architecture is the preferred way of architecting application 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 application at the run time.

Any external dependency like database access and the web service call are part of the external layers

UI is part of the external layers

Objects representing domain 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

Internal layer should not depend on the external layers.

Domain object which is at the core or centre can have access to the both the UI and the database layers.

All the coupling are towards the centre

Codes which may change often should be part of the external layers

Project structure

Let us start with creating the solution structure. We are going to work with the four projects.

Core project (Class library )

Infrastructure project (Class library)

Test project (Unit Test project)

Web project (MVC project)

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

Solution structure should look like as listed in the below image.

Core project

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

Usually the core project should contain,

Domain entities

Repositories interfaces

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

Reference of the ORM like LINQ to SQL or EF

Reference of ADO.NET libraries

Reference of Entity Framework etc.

Create Entity

Let us go ahead and create BloodDonor entity class.

We may have a requirement to have some restrictions on the entity properties. For example maximum length, required etc. We do have two choices to achieve this,

Using System.ComponentModel.DataAnnotations

Use Entity Framework fluent API.

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

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 are going to follow the repository pattern. Roughly repository pattern allows us to replace the database access codes (class) without affecting the other layers. In the repository interface we will put definition of all the database operations need to perform.

As of now we have created the domain entity and the repository interface. Next let us go ahead and create the infrastructure project.

Infrastructure project

In the infrastructure project we perform operations related to outside the application. For example,

Database operation

Accessing outside service

Accessing File systems

Above operations should be part of the infrastructure project. We are going to use the Entity Framework to perform the database operations. We are working with the Entity Framework code first approach, so we need to perform the following steps,

Create the data context class

Implement the repository class

Create the data base initializer class

Before we go ahead and create the data context class, let us go ahead and add reference of the Entity Framework. To add the reference right click on the infrastructure project and select manage Nuget package. From Nuget package manager select the Entity framework package to install in the project.

DataContext class

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

Connection string

Optionally either you can 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 go ahead and set the connection string as shown in the below listing,

Database initialize class

We want database to initialize with some initial values. It can be done as shown in the below listing,

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. Repository class will access the database using the LINQ to Entity. To create the BloodDonorRepository class let us go ahead and create a class which will implement the IBloodDonorRepository interface.

To implement the repository class, we are using the LINQ to Entity for the database operations. For example to add a blood donor,

Create object of context class

Use context.entiy.Add(entity)

Use context.SaveChnages()

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

Directly MVC project or should we write 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 selection Unit Test project template from the Test project tab. To start writing test, very first in the unit test project we need to add following references

Reference of the core project

Reference of the infrastructure project

Entity framework package

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 listing below,

In the test setup, we are creating instance of BloodDonorInitalizeDb class and then setting up the database with the initial values. Also in the test setup, instance of repository class is created. Next let us create test to validate whether data base is initialized with the right number of data or not.

In the test above we are calling the GetBloodDonors method of the repository class and then verifying the number of records. In ideal condition above test should be passed. You can verify the test result in Test-Window-Test Explorer

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

Web Project

We are going to create MVC project which will use the core project and the infrastructure project. Add following reference in the MVC project

Reference of infrastructure project

Reference of core project

Entity framework package

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

Also we need to select the following options,

BloodDonor class from the core project as the Model class

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 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 instance of BloodDonorInitalizeDb class and set the database. We need to write this code inside the global.asax .

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 copy the connection string in the web.config

At this point if we run the application we should 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 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 creation of 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 database access program then 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 two options to use the repository class

Directly create the object of repository class in the controller class

Use dependency injection to resolve repository interface to the concrete repository class object at the run time using the unity container.

We are going to use the second approach. To use the unity container add Unity.Mvc5 package in the web project using the 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 in the below image add the register.

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

So far we have added the unity container reference and register the type. Now let us go ahead and refactor the controller class to use the repository class. To start with

Create a global variable of the type IBloodDonorRepository

Create controller class constructor with a parameter as shown in below image

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

After refactoring the BloodDonorController class will look like as shown in below listing,

Conclusion

This is it. These are the steps we need to follow to create a MVC application following to onion architecture.

Source Code on the GitHub

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

Filed under: MVC

Show more