Step by Step implementing Onion architecture in ASP.NET MVC Application

Source Code on the GitHub

Learn Creating N-Tier Applications in C#, Part 1 by Steve Smith here – I learnt lot from this course hence sharing
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.

image

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.

  1. Core project (Class library )
  2. Infrastructure project (Class library)
  3. Test project (Unit Test project)
  4. 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.

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.


public class BloodDonor
    {
       public string BloodDonorID { get; set; }
       public string Name { get; set; }

       public DateTime Dob { get; set; }

       public string BloodGroup { get; set; }

       public string City { get; set; }

       public string Country { get; set; }

       public int PinCode { get; set; }

       public string PhoneNumber { get; set; }

       public string Email { get; set; }

       public bool IsActive { get; set; }

       public bool IsPrivate { get; set; }

       public bool IsVerified { get; set; }

    }

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,

  1. Using System.ComponentModel.DataAnnotations
  2. 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,

using System;
using System.ComponentModel.DataAnnotations;

namespace LifeLine.Core
{
   public class BloodDonor
    {
       [Required]
       public string BloodDonorID { get; set; }
       [Required]
       [MaxLength(50)]
       public string Name { get; set; }
       [Required]
       public string BloodGroup { get; set; }
       [Required]
       public string City { get; set; }

       public string Country { get; set; }
       [Required]
       public int PinCode { get; set; }
       [Required]
       public string PhoneNumber { get; set; }

       public string Email { get; set; }

       public bool IsActive { get; set; }

       public bool IsPrivate { get; set; }

       public bool IsVerified { get; set; }

    }
}

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.


using System.Collections.Generic;

namespace LifeLine.Core.Interfaces
{
    public interface IBloodDonorRepository
    {
        void Add(BloodDonor b);
        void Edit(BloodDonor b);
        void Remove(string BloodDonorID);
        IEnumerable<BloodDonor> GetBloodDonors();
        BloodDonor FindById(string BloodDonorID);

    }
}

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,

  1. Create the data context class
  2. Implement the repository class
  3. 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.


using System.Data.Entity;
using LifeLine.Core;

namespace LifeLine.Infrastructure
{
   public class BloodDonorContext : DbContext
    {
       public BloodDonorContext()
           : base("name=BloodDonorContextConnectionString")
       {
           var a = Database.Connection.ConnectionString;
       }

       public DbSet<BloodDonor> BloodDonors { get; set; }
    }
}

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,


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

Database initialize class

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

using System;
using System.Data.Entity;
using LifeLine.Core;

namespace LifeLine.Infrastructure
{
   public class BloodDonorInitalizeDb : DropCreateDatabaseIfModelChanges<BloodDonorContext>
    {

       protected override void Seed(BloodDonorContext context)
       {
           context.BloodDonors.Add(
           new BloodDonor
           {
               Name = "Rahul Kapoor",
               City = "Gurgaon",
               BloodGroup = "A+",
               BloodDonorID = "BD1",
               Country = "India",
               IsActive = true,
               IsPrivate = false,
               IsVerified = true,
               PhoneNumber = "91+7378388383",
               PinCode = 122002,
               Email = "Rahul@abc.com"

           });
           context.BloodDonors.Add(
               new BloodDonor
               {
               Name = "Salman Khan",
               City = "Mumbai",
               BloodGroup = "A-",
               BloodDonorID = "BD2",
               Country = "India",
               IsActive = true,
               IsPrivate = false,
               IsVerified = true,
               PhoneNumber = "91+84848484",
               PinCode = 25678,
               Email = "Salman@abc.com"
               }
       );
            base.Seed(context);
       }
    }
}

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.


using System.Collections.Generic;
using System.Linq;
using LifeLine.Core;
using LifeLine.Core.Interfaces;

namespace LifeLine.Infrastructure
{
   public class BloodDonorRepository : IBloodDonorRepository
    {
       BloodDonorContext context = new BloodDonorContext();
        public void Add(BloodDonor b)
        {
            context.BloodDonors.Add(b);
            context.SaveChanges();
        }

        public void Edit(BloodDonor b)
        {
            context.Entry(b).State = System.Data.Entity.EntityState.Modified;
        }

        public void Remove(string BloodDonorID)
        {
            BloodDonor b = context.BloodDonors.Find(BloodDonorID);
            context.BloodDonors.Remove(b);
            context.SaveChanges();
        }

        public IEnumerable<BloodDonor> GetBloodDonors()
        {
            return context.BloodDonors;
        }

        public BloodDonor FindById(string BloodDonorID)
        {
            var bloodDonor = (from r in context.BloodDonors where r.BloodDonorID == BloodDonorID select r).FirstOrDefault();
            return bloodDonor;
        }
    }
}

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

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

 


BloodDonorRepository repo;
        [TestInitialize]
        public void TestSetUp()
        {

            BloodDonorInitalizeDb db = new BloodDonorInitalizeDb();
            System.Data.Entity.Database.SetInitializer(db);
            repo = new BloodDonorRepository();
        }

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.

[TestMethod]
        public void IsRepositoryInitalizeWithValidNumberOfData()
        {
            var result = repo.GetBloodDonors();
            Assert.IsNotNull(result);
            var numberOfRecords = result.ToList().Count;
            Assert.AreEqual(2, numberOfRecords);
        }

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

clip_image002

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

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

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

image

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.

image

 

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 .


BloodDonorInitalizeDb db = new BloodDonorInitalizeDb();
            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 copy the connection string in the web.config


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

At this point if we run the application we should able to perform the CRUD operations.

image

 

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.

clip_image002[6]

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

  1. Directly create the object of repository class in the controller class
  2. 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.

image

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.

clip_image002[8]

 

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

clip_image002[10]

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

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

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,

image

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

 


using System.Linq;
using System.Net;
using System.Web.Mvc;
using LifeLine.Core;
using LifeLine.Core.Interfaces;
namespace LifeLine.Web.Controllers
{
    public class BloodDonorsController : Controller
    {
        IBloodDonorRepository db; 

        public BloodDonorsController(IBloodDonorRepository db)
        {
            this.db = db;
        }

        // GET: BloodDonors
        public ActionResult Index()
        {
            return View(db.GetBloodDonors().ToList());
        }

        // GET: BloodDonors/Details/5
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BloodDonor bloodDonor = db.FindById(id);
            if (bloodDonor == null)
            {
                return HttpNotFound();
            }
            return View(bloodDonor);
        }

        // GET: BloodDonors/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: BloodDonors/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "BloodDonorID,Name,BloodGroup,City,Country,PinCode,PhoneNumber,Email,IsActive,IsPrivate,IsVerified")] BloodDonor bloodDonor)
        {
            if (ModelState.IsValid)
            {
                db.Add(bloodDonor);
                return RedirectToAction("Index");
            }

            return View(bloodDonor);
        }

        // GET: BloodDonors/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BloodDonor bloodDonor = db.FindById(id);
            if (bloodDonor == null)
            {
                return HttpNotFound();
            }
            return View(bloodDonor);
        }

        // POST: BloodDonors/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "BloodDonorID,Name,BloodGroup,City,Country,PinCode,PhoneNumber,Email,IsActive,IsPrivate,IsVerified")] BloodDonor bloodDonor)
        {
            if (ModelState.IsValid)
            {
                db.Edit(bloodDonor);
                return RedirectToAction("Index");
            }
            return View(bloodDonor);
        }

        // GET: BloodDonors/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            BloodDonor bloodDonor = db.FindById(id);
            if (bloodDonor == null)
            {
                return HttpNotFound();
            }
            return View(bloodDonor);
        }

        // POST: BloodDonors/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            BloodDonor bloodDonor = db.FindById(id);
            db.Remove(bloodDonor.BloodDonorID);
            return RedirectToAction("Index");
        }

    }
}

 

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.

How do I setup ASP.NET Identity 2.0 to use my own connection string

By default ASP.NET Identity 2.0 creates the database inside the App_Data directory of the application. ASP.NET identity 2.0 works on the Entity Framework Code First approach and it reads the connection string mentioned in the web.config as shown below,

clip_image002

In the ApplicationDbContext class you can find that connection string named DefaultConnection has been used. You can find ApplicationDbContext class inside the IdentityModels.cs file.

clip_image003

You may have a requirement to use some other database server and the database to configure the ASP.NET Identity 2.0. Simplest way you can do this by changing the connection string the web.config file.

clip_image005

DJPC is database server name of my development machine. ASP.NET Identity 2.0 works on the EF Code First approach, it will create the database DelhiDevDayExample, if it’s not already there. Other option is to create connection string programmatically and pass it to the context class.

This is the way you can change the connection string of ASP.NET Identity 2.0.

Hindi Video : Create Azure based ASP.NET MVC application in 30 minutes

 

Subscribe here to YouTube channel for all episodes

image

Cloud has been a buzz word for a while now. As a developer, we focus on converting the customer requirements to the code and sometimes find ourselves behind with the industry buzz words. The cloud is everywhere and perhaps the future. However as a developer, you won’t have to write very different code for cloud than codes you have been writing for the in-premise applications. In this post, I assume that you are already aware about MVC applications, hence I will focus on demonstrating how building for cloud is not very much different. I will follow step by step approach and create end to end MVC application completely hosted in the cloud (data and application both).

In this article, we will follow the following steps,

  • Setting up the database in the SQL Azure
  • Creating the MVC application
  • Building the application using MVC and the Entity framework
  • Publishing the application to Azure web site

Read full article on Infragistics blog

Subscribe here to YouTube channel for all episodes

 

 

 

 

 

Read article based on this video here

Subscribe here to YouTube channel for all episodes

I hope you like this video. Do not hesitate to leave comment or any feedback. Happy coding.

How to create a Container in Azure Storage from MVC application

I am working on a MVC application in which I need to work with Microsoft Azure storage .I had a requirement to create An Azure storage container from the MVC application. In this post I will share my learning that how I created a container programmatically.

I created the view as shown in below image. User has to enter the azure storage account name, azure storage key and the name of the container to be created.

image

Above View is MVC razor view, and it is created using the cshtml as shown below:

 


@{
    ViewBag.Title = "BLOB Manager";
}
<div class="jumbotron">
    <div class="row">
        <div class="col-md-8">
            <section id="loginForm">
                @using (Html.BeginForm("AzureInfo", "Manage", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                {
                    @Html.AntiForgeryToken()
                    <h2> Manage BLOB Container</h2>
                    <hr />
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountName", "", new { @class = "form-control", @placeholder = "Account Name" })
                            @Html.ValidationMessage("AccountName", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountKey", "", new { @class = "form-control", @placeholder = "Account Key" })
                            @Html.ValidationMessage("AccountKey", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("ContainerName", "", new { @class = "form-control", @placeholder = "Container Name" })
                            @Html.ValidationMessage("containername", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group input-group input-group-lg">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create Container" class="btn btn-lg btn-success" />
                        </div>
                    </div>

                }
            </section>
        </div>
    </div>
</div>

Above I am creating,

  • Three text boxes with the placeholder and the class set to bootstrap form-control
  • A submit button with the class set to bootstrap btn-lg and btn-success
  • All the controls are inside the form.
  • On form post operation, AzureInfo action of the Manage controller will be called.

Once the View is ready, let us go ahead and create an azure utility class. In this class we will put all the operations related to the azure storage. But before that you need to add Azure storage library to the project. Either you can use NuGet package manager or console to add the library. I am using console to install Azure storage library. I have taken the 4.3 version because at the time of writing this post, this was the latest stable version available.

image

Once package is successfully installed, add following namespaces.

 


using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;

To create the container in the Azure storage, I have created a function CreateContainer. This function takes three input parameters, account name, account key and the container name.

 


public static class AzureUtility
    {
        public static string  CreateContainer(string AccountName, string AccountKey, string ContainerName)
        {

            string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(UserConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
            if (container.CreateIfNotExists())
            {
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                return container.Name;
            }
            else
            {
                return string.Empty;
            }
        }
    }

Now let us examine the above code line by line.

  • In first line I created the connection string for the azure storage. It takes two parameters, account name and the account key. These values are passed as input parameter to the function. I am using these two parameter to create connection string.
  • Using CloudStorageAccount to parse the connection string from the constructed string.
  • Creating the CloudBlobClient
  • Getting the container reference of the BLOB.
  • If container reference does not exist, creating new container.
  • On successful creation of the container function returns name of the container else empty string.

 


[HttpPost]
        public ActionResult AzureInfo(string AccountName, string AccountKey, string ContainerName)
        {

           var result= AzureUtility.CreateContainer(AccountName, AccountKey, ContainerName);

           if (result != string.Empty)
             {

                 return RedirectToAction("Index", "Home");
             }
             else
             {
                 return RedirectToAction("Index");
             }
        }

In the action we are using the utility class to create the container. In this way an azure container can be created from the MVC application.

I hope it is useful. Thanks for reading. Happy Coding.

Child Actions in ASP.NET MVC

Read full post on falafel blog

Child Actions are the action methods which can be invoked within the view. This is used to work with the data in the view, which are not related to the main action method. For example, if you want to create a data driven widget in the view using data that is not related to the main action method, you will need to use the child action method.
In ASP.NET MVC any action can be used as a child action. However, to use an action only as a child action and attribute it with the ChildActionOnly. It will make sure the action is not called by any user request and will only be used in the view. A child action can be created as shown below:

Read full post on falafel blog