Onion architecture with MVC using repository pattern

Finally i am up with my article related to onion architecture. The main aim of this article is try to learn the onion architecture and have a sample sample code which is loosely coupled and easily maintainable. So to learn this concept efficiently, our application would consist of following:

  • An mvc application using Onion architecture.
  • Entity framework with database first approach.
  • Dependency injection using Unity container.
  • Repository pattern with a repository per entity.

So let’s start with some of the basics.

What is Onion architecture ?

This architecture term was coined by Jeffrey Palermo back in 2008. Long time since then and it has become very popular these days. When you get into the details of this architecture, you might feel that you were already using from long time but may not be aware of that.

Just a quick introduction to it. Onion architecture is the way of designing your application layers in such a way that, like an onion, the innermost layer or the core component, we can say, is independent of the layer above it. As we move away from the core, the layers/components can depend on the layer towards the core but not on the layers above itself. For example, if we have 3 layers of architecture, and Layer1 is the innermost or the core layer, then Layer2 and then Layer3. So, to create an onion architecture based application would have Layer1 as the innermost layer, independent of Layer2 and Layer3. Then Layer2 comes above Layer1 and depends on only Layer1 and NOT Layer3. Finally, Layer3 is the outermost layer and can depend on both Layer1 and Layer2.

So the most important point in the onion architecture is that as we move from core to the top most layer, the dependency towards the inner layers increases. But there should not be any inter-dependency between the layers i.e. Layer2 should not depend on Layer3. So we should try to keep the core layer as much generic as possible, though not necessary always. In such a case, our architecture layers would look like the following:

Onion Architecture & Dependency Injection using Unity

Let’s try to understand by creating a new MVC application. We will create an application with tight coupling, and try to convert into Onion architecture with the system of loosely coupled components. Fire up your visual studio and add a new project of type MVC.

Onion Architecture & Dependency Injection using Unity

Next we will display some sample data on a page, from database. For this, we will create a sample database and use the entity framework database first approach. So let’s add an .edmx and update it from a sample database. But, adding this edmx to the same project does not makes a good sense, as the models will be tightly coupled to the UI layer. So what we will do is that we add a new project layer of type class library, with the name SampleArchitecture.Infrastructure and add the .edmx to it. See the code below:

Onion Architecture & Dependency Injection using Unity

Next, in order to display the data from the table, we create a new class called UsersRepository.cs, in the same Infrastructure project, which will have the methods for CRUD operations related to the Users table. For our example, we will add a simple method GetAllUsers, which will get all the records from the Users table. See the code below:

Onion Architecture & Dependency Injection using Unity

Now let’s add a controller, its corresponding view, and make a call to the repository GetAllUsers method. In order to access the repository, we need to add reference to the Infrastructure project. So add the reference to it and call the method as:

Onion Architecture & Dependency Injection using Unity

Now bind the Model in the View, run the application and see the results.


Looks good so far. But there are few issues in this code.

1. Violation of Single Responsibility Principle: The controller class is dependent on the concrete UserRepository class. The issue is that the Controller method is now responsible for multiple tasks, i.e. instantiating the repository and returning the view with the data. This violates the S of the SOLID principles, which says that each class/function should be responsible or only one task.

2. Tight coupling between the Web and the Infrastructure project:  Our web project is directly dependent on the entities. This includes not only the Controller class but also the View (as the View will use the Model property to bind the data). So in future, for some reason, we need to remove the use of entity framework, it will not only affect the Infrastructure project but also the web application as we directly refer the entities into the Controller and View.

3. Concrete Repository class: UserRepository is concrete class in the project. As a result, where-ever, it will be used in the project, it will increase coupling between the components.

Onion Architecture & Dependency Injection using Unity

So let’s start by reducing the tight coupling caused by the use of the entity framework with View and Controller. So what can we do here ? We introduce plain POCO classes, which will carry the data from the data access layer, through repository, to Controller and then finally the View. But a very important thing to be decided, where to add these POCO classes. The reason being, we are trying to use the onion architecture. We can add them to the Infrastructure project. But the point is that, these classes are just required to be container classes, carry the data and bind with the UI. So why not isolate them to another independent layer. So we add another layer called SampleArchitecture.Core,  and add its reference in the Infrastructure and the web layer. This will be also in sync with the onion architecture, where

1. Core layer will be independent of the Infrastructure and Web layers. This becomes Layer1 of our earlier discussion.

2. Infrastructure layer will be independent of the Web layer, but will be dependent on the Core layer, for the POCO classes. This becomes Layer2 of our earlier discussion.

3. Web layer will be dependent on both the Core and the Infrastructure layers, for the use of POCO classes and the repository classes. This becomes Layer3 of our discussion earlier.

So let’s add a new project of type ClassLibrary and add a POCO class called UserUI. Another advantage of these classes is that we can add the validations of the model here itself.

Onion Architecture & Dependency Injection using Unity

Next, we change the repository method to use the POCO class and return the same to the Controller and bind it with the View.

Onion Architecture & Dependency Injection using Unity

Run the application and now you can see the results.

Onion Architecture & Dependency Injection using Unity

So now even if you need to remove the entity framework, just need to make changes in the Infrastructure layer. No need to change the Controller method or the View binding and hence no changes in the Core and Web layers.

Now, we will try to remove the process of creating the instance of the repository class, within the controller. For this, we will use the concept of Inversion of ControlThis means, we will invert the controllers’ responsibility of initializing the repository from the Controller, to any other locationThis will be done by one of the dependency injection container named Unity. So basically this dependency injection container will be responsible for creating the required dependency and passing it to the controller. As per MSDN, Unity is:

Unity is a general-purpose container for use in any type of Microsoft.NET Framework-based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods, and as the value of properties of objects it resolves.

In order to use it, we need to add reference to the unity dll’s using the nuget package manager. This is to be added in the Web project, as we need to inject the dependency on the controller methods. Let’s start by adding the reference to the unity dll’s.

Onion Architecture & Dependency Injection using Unity

Next, we add an interface named IUserRepository add the definition of GetAllUsers method. Implement this interface on the UserRepository class. Again the same question, where to add the interface ? And same concept to answer this question, this is a re-usable component and should be an independent component. So we add it to the SampleArchitecture.Core project. Makes sense, doesn’t it ? So the code changes to:

Onion Architecture & Dependency Injection using Unity

Now the controller needs the instance of the UserRepository, which will be provided by the UnityContainer. As the name suggests, unity container is like a container which is responsible for providing the required dependency to a class. In our example, we need the UserRepository instance. So unity container will provide it, to us. But before it can do that, we need to register the required dependencies with the container. Registering the dependency is like telling the container that when i am using this interface, provide me an instance of the concrete class that implements this interface. At run time, get the required dependency from this container and inject to the required method using the Constructor, Property or Method injection process.

So for this, we add a class named UnityConainerRegistration and register the dependencies. We add this class in the main web project as this is where we need the dependencies to be resolved.

Onion Architecture & Dependency Injection using Unity

Next, we initialize this container in the Global.asax file. So when the application is started, it will register all the dependencies in the container.

Onion Architecture & Dependency Injection using Unity

Finally, we change our Controller to receive the dependency of UserRepository, using the Constructor, in the form of IUserRepository (as it implements this interface). This dependency gets resolved through the unity container we registered above.

Onion Architecture & Dependency Injection using Unity

So now run the application and there is no affect on the results. But in the application code, our the dependency follows what we aimed at i.e. the onion architecture. Our SampleArchitecture.Core is the innermost layer which is independent of everything. Then we have the SampleArchitecture.Infrastructure, which is dependent on the Core layer and independent of the web layer. Finally we have the web layer which is dependent on both the Core and the Infrastructure layer. This is what we aimed at:

Onion Architecture & Dependency Injection using Unity

So this is what we discussed in the starting. Wasn’t that easy to learn. Hope you enjoyed reading it. Happy coding…!!!

Posted in Design and Architecture | Tagged | Leave a comment

My understanding of OWIN and Katana

I have been trying to learn these concepts from a long time. Read many good articles, their definitions, but could not make much out of them. Finally, I decided to write my understanding that I have got from these resources. So in this article, I will share my learning about what are O.W.I.N. and Katana and will also try to get into some basic details that makes them important concept to be learnt. So let’s start with their basic definitions first.

What is O.W.I.N. ?

O.W.I.N. stands for Open Web Interface for .Net. Note that this is just a specification and not any technology or framework. It’s official definition is quite simple and easy to understand. It says:

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.

Let’s try to understand what this definition is trying to convey here. Till now the developers mainly focused on decoupled application code by creating different layers in the applications, which interact with the use of interfaces, use design patterns, S.O.L.I.D. principles etc. But O.W.I.N. is a step above the code decoupling. It is aimed at decoupling the application and the web-server, that hosts the application. Using such kind of decoupled architecture allows:

1. Creating middleware components which can be replace/added in the application without affecting the other components in the application
2. Remove the dependency of web server to host a component, by promoting the use of self-hosting.

We will discuss about these points, later in the discussion.

What is Katana ?

Next the question comes what is Katana and how it is related to the OWIN ? The answer is that if OWIN is a specification (and not any technology or framework), than Katana is an open source project by Microsoft based on the OWIN. One such example is the asp.net webapi, based on the OWIN specifications, supports the concept of self-hosting for hosting, by using the OWIN custom hosts(we will see the custom host concept in further discussion) and eliminating the dependency on IIS for hosting.

So to conclude this part of the discussion, OWIN is a specification and Katana is Microsoft’s open source project which uses these specifications.

So moving on, let’s discuss in details about OWIN. But before that, a very important point to be mentioned, which will make further understanding easier. For this, I would like to quote a very good explanation about what OWIN is, from the link here. It says:

OWIN introduction allowed any OWIN-compatible application to talk through OWIN to a web server that had an OWIN-compatible hosting layer. Microsoft wrote Katana as one OWIN implementation that could host ASP.NET Web API, ASP.NET SignalR, and many 3rd party frameworks on top of several servers, including IIS (and IIS Express), Katana's self-host server, and custom hosts (i.e. run Katana's host in a custom app).

This means that Microsoft’s Katana project allows the use of the OWIN specifications by providing not only new servers like Katana’s self host server, custom host server (like any windows service or console application) but also with existing web servers like IIS & IIS express.

In any normal asp.net application architecture, we have different layers categorized as host, server and the main application. In such a case, IIS acts as the server as well as the host. But in case of any OWIN based structure, we can have 4 different layers. Three of these layers are web server, OWIN compatible applications like SignalR and Webapi and OWIN compatible hosting layer. The 4th one is our main application which could be any application based on web-forms or mvc framework. So the structure defined above is layered as:


Let’s discuss these layers in detail now.

The Host layer: In any OWIN specifications based application, this layer can consist of either of the following 3 acting as the host:

  • IIS : This includes the use of IIS as the host for any application. In such as case, Microsoft.Owin.Host.SystemWeb is to be used as the Server. This will allow to add any OWIN compatible component or middleware to be easily added/remove from the pipeline.
  • Custom Host: This involves creating a windows service or a console application and using it to host your OWIN compatible applications like SignalR or Webapi. An example is self-hosting the webapi in a Console or windows application. See an example here. 
  • OwinHost.exe: This is an executable file named OWIN.exe. It can be directly run and used as a host for any application.

The Server Layer: Next we have the server layer, which will listen to any incoming requests and manage the requests in pipeline. This layer can be based on:

  • Microsoft.Owin.Host.SystemWeb: System.Web is used when we are using IIS as the host. In that case, IIS also acts as the server. So in order to easily plug the  OWIN components in the pipeline, we can use this server layer. A definition from one of the reference links defines its role as:

The Katana SystemWeb host registers an ASP.NET HttpModule and HttpHandler to intercept requests as they flow through the HTTP pipeline and send them through the user-specified OWIN pipeline.

  • Microsoft.Owin.Host.HttpListener: This involves the use of .Net frameworks’ HttpListener class to open a port and manage the request pipeline.

Using these two layers, suppose we add a new empty application project and try to create an application based on this structure. In this case we have two different options:

  • By using Microsoft.Owin.Host.SystemWeb as the server implementation, we make use of IIS as the host as well as the server.
  • By using Microsoft.Owin.Host.HttpListener  as the server implementation, we can use any custom host like windows or console application as the host or even the OWIN.exe executable as the host.

Middleware Components: These are the OWIN compatible components like SignalR and WebAPI and even static html pages. These are added to the system as plug and play components and can be easily added/removed without affecting the other modules. When the server receives any request from the client, it is passed through these components.

Applications: This could be any of your ASP.Net, mvc or any other applications.

Now let’s try to create a sample using the above concepts. So we will use

1. Custom host in the form of a Console application.
2. Microsoft.Owin.Host.HttpListener for the server implementation. 
3. WebAPI and an HTML page as the middleware components in the system. An option could have been using any mvc or asp.net page as separate application in place of the html page. Then it would have acted as the 4th layer of the system i.e. Main Application. Another important point is, using any asp.net or mvc would not have been a good option as this would than not be hosted through custom host or used the Microsoft.Owin.Host.HttpListener server implementation. This is the reason i have highlighted it to be used as a separate application.

Start by adding a new console application. This will  be the first layer or the custom hosting the system, instead of IIS. Add the references to the Microsoft.Owin.Host.HttpListener by using the nuget package manager. This would then meet the requirement of a server implementation.  


So we have the host and server in place. Next, we need to add the middleware component webapi. So we add reference to the webapi2.2 OWIN package, using the nuget package manager and OWIN hosting libraries.

OWIN and Katana

OWIN and Katana

Next, we add another middleware component. This time, its libraries to add support for hosting html pages. Yes that’s correct. We will host html pages in a console application. So let’s see how we can do this.



Now we have all the required references in the project and just need to configure the components to be used. Before that, we add a webapi controller and an html page into a folder named Pages. So our complete solution structure will like the following:

OWIN and KatanaSo now let’s configure these components one by one. First, add a simple method in webapi controller, which returns the current date-time string. This will be called from the html which we added above.

OWIN and KatanaNext, we will register our middleware components i.e. webapi and the html file in the WebAPIConfig.cs. This will make the hosting of the webapi and the html file possible.  See the code below:

OWIN and Katana
Next, let’s start the server and host the application. For this, add the following code the Main function in Program.cs

OWIN and KatanaFinal step, add some html to the html page and call the webapi method to get the date from the server.

OWIN and Katana
All done. Now start the console application and you can than browse the html page on the same url, as that of web api. Click the button and your request will be sent to the webapi.

OWIN and Katana

So now you can host the html page in the console application as well. Further if you tomorrow if you need to ad the SignalR functionality, simply add the references and configure it in the WebAPIConfig.cs file like we did for the webapi and the static files.

Further, if we need to provide the service api to any third party, simply host that in the console application or windows service. No dependency on the IIS.

Following are some of the reference links you may find useful:

1. Basic concept of Host, servers and middleware 
2. Use IIS as host and SystemWeb as the server for OWIN implementation 
3. http://stackoverflow.com/questions/25431750/asp-net-vnext-is-host-agnostic-what-does-it-deeply-mean
4. Step by step configuring components in OWIN pipeline.

Hope you will find this article helpful and enjoyed reading it. Happy coding…!!!

Posted in OWIN & Katana | Tagged | Leave a comment

Real time data update using SignalR

In my last article, we discussed about the concept of SignalR and how we can use it to create a simple web based group chat. It included a good deal of explanation of what and why SignalR is a good candidate to create a real time application. We will not get into details again and before you start with it, I would recommend you to read my previous article here. Our this discussion will be another practical implementation of what we had learnt in the last article.

Let’s create another sample application to demonstrate the use of SignalR. This application will be an html page, which displays some data from the database.  At the back-end of this sample, we will have another application, say any form, windows service or RSS feed, which will insert the new data into the database. As soon as the new data is added to the database, that will be reflected on this html page.

An important point before we start the discussion is that this example will not only use the SignalR, but also the concept of SqlDependency, so that our server hub get’s notified about any change in the database and broadcast the latest data to the users. To describe the logic briefly, our hub will subscribe to SqlServer for any change in its data in the database, get notified, fetch the latest data and broadcast it to the html page. So our application will consist of following 3 separate components.

  • Sample table called Users in a Sql database, with its ServiceBroker enabled.
  • An application with a html page to display the list of users from the database. This will also include a webapi which receive data from a third application and save it into the database and a SignalR component to broadcast the latest data to the users.
  • An application with an html page to submit new data to the database by making calls to the webapi.

So our overall application flow will be like the following:

Realtime data using SignalR

Database setup: Create a new table named Users, in a sample database. In order to use the SqlDepedency, we need to enable the ServiceBroker for the database. This can be done by using the following command:


or, from the UI by selecting the database, right click on its properties, go to the Options, navigate to the Service Broker section and change the value to True for Broker Enabled property.

Enable service broker

Create the main application: This application will consist of following components:

1. Webapi to receive the data from the data feed application and save into the database.
2. An html page to display the data from the database.
2. SignalR component which will refresh the html page with latest data, as soon as the new data is added to the database.

Let’s create a Webapi which can receive the data from the user and store it in the database. For this, we add the references to the WebApi2 and OWIN packages, using the nuget package manager. Once the references are added, we add a new class file of type Web API Controller class. Let’s call it DataFeedController.cs. Add a POST method to receive the data from the user and store it in the database, using the entity framework.So our controller would look like below:

Realtime data using SignalR

Now in order to host the Webapi and SignalR, we add a file named Startup.cs and add the routing template for Webapi and register both the webapi and SignalR to the OWIN pipeline. When we start the application, it will result in hosting of the Webapi at the back-end.

Realtime data using SignalR

Now in order to add the real-time functionality to the application we add a class named RealtimeDataHub.cs, derived from the Hub class and will be used as a middleware between the database and the html page (which is used to display the data). We will not get into what this hub class is and its role, as we discussed about it in the previous discussion here. This class will have a method named GetUsers() which will get the data from the database and broadcast it to the connected users. Inside this method, the hub also subscribes to the sql for getting notifications for change in the database, using the OnDependency change event of the SqlDependency class. See the code below:

Realtime data using SignalR
Create data feed application: Create a new  empty project and add an html page to it. This html page will have 3 textboxes and a button to store the data in the database, by calling the WebApi created in step 1 above. We will call it as data feeder application. In a real time scenario, we can have any windows service which is fetching data using some api and storing it in the database. So our html mark up will be like below:

Realtime data using SignalR

Next, use the ajax call to send the data to the webapi controller, which stores it in the database.

Realtime data using SignalR

Note that here we have used the localhost url to refer to the location where the web api is hosted. You can replace it with the actual url of the WebApi location.

So our setup is complete now. In order to start the application, first run the html page of the main application, which displays the data from the database. When this application is started, its corresponding web api also gets hosted. First time, there will be no data. So let’s start the data feeder application also and add some data. Add the new data and Save it. As soon as the new data is added, it immediately gets reflected in the main applications home page. See below:

Realtime data using SignalR


So now need to use timer based calls. Use the SignalR functionality and create real time applications. Hope you enjoyed reading it. Happy coding…!!!

Posted in advanced concepts & industry trends, SignalR | Leave a comment

Implicit vs Explicit interface implementations

It’s a very small but very important concept to be learnt. It’s very normal to use the interfaces in our applications. But at the same time, it’s very important to make sure that these interfaces are implemented correctly. So whenever we implement an interface in C#, we get two different to implement it i.e. either Implicitly or Explicitly:

Implicit and Explicit interface implementations in C#

But what’s the difference between the two. To understand it in better way, let’s first create two classes and implement an interface implicitly for ClassA and explicitly for ClassB.

Implicit and Explicit interface implementations in C#

Now let’s create another class ClassC and try to access the GetData method of both these classes i.e. ClassA and ClassB. Can we access that method for both ? See the code below:

Implicit and Explicit interface implementations in C#

We can do it for ClassA but not for ClassB. This is the main difference between the two implementations. For any explicitly implemented interface, you cannot access the interface methods until you create the instance of the class to be of particular interface type. Now let’s instantiate the ClassB instance as ISampleInterface type and try to access the method.

Implicit and Explicit interface implementations in C#

This time it’s accessible. Now the question is when to use explicit interface implementation. Following are some of the points that can help us to decide which to use when.

1.  Suppose you have a DLL of some API for your clients. This includes a class which implements two interfaces ISampleA and ISampleB. ISampleA is using the methods of ISampleB for some functionality, however the client has no concern with ISampleB methods as he is using ISampleA. Now is this wise enough to expose the methods of ISampleB through the use of the implicit interface implementation. So the idea should be to use implicit implementation for ISampleA and explicit implementation for ISampleB.
But of-course, if the client get’s to know about ISampleB interface, he can create the instance of the class to be of type ISampleB and access its methods.

2. Another scenario, both your interfaces have a common method GetData() or even your class has a method named GetData(). Implicit implementation of interfaces will not allow you to do this. You will error something like the one below:

The call is ambiguous between the following methods or properties: 'InterfaceImplementations.ClassA.GetData()' and 'InterfaceImplementations.ClassA.GetData()' 

So these are two cases which I think help you decide whether to use implicit or explicit interface implementation.If you have any other than do share with us. Happy coding…!!!

Posted in C#, Interview Questions, Object Oriented Programming | Leave a comment

Tuples in C#

Any function we use in C# can return maximum of single value which can be string, int or any other type, as per our requirements. If more than one value is to be returned, we use different types of approaches, like using any Dictionary with key-value pair, or any new container class, with properties of this class being the data/parameters we would like to be returned from that function or use the out or ref based parameters. All these are good if they are fulfilling our requirements. But C# provides a Tuple class, which can be used as more efficient way of returning multiple values from a function.

Tuples were introduced in C# 4.0. In simple terms, you can define a tuple as a single record of different types of data. For example, a single record with UserId, FirstName, LastName, Salary etc can be called as a tuple. It’s not necessary that all these attributes are of the same user. UserId can be of one user, FirstName could be of another user, Salary could be of third user and so on.

Enough of theory, let’s do some practical. There are two different ways how a tuple can be created. First is simply creating a new instance of the Tuple class and explicitly specifying the types of elements this tuple can have. The values to be stored in this tuple are passed in its parameterized constructor. See the code below:

Tuples in C#Accessing the parameters is very easy. Just use _tuple.Item1, tuple.Item2 where Item1 and Item2 are the elements at the first and second position of the tuple. See the code below:


Tuples in C#

So the complete code becomes:


Another way to create a tuple is use the Create method of the tuple class. However, the method to access the elements remains the same. See the code below:

Tuples in C#

So these were two different ways of creating a tuple. An important point, there is a limit of 7 elements that a tuple can hold. The eighth element can only be another tuple. Although if you try to declare an eighth element of any type other than a tuple type, there will be no compile time error. But it will break at run-time with the error:

The last element of an eight element tuple must be a Tuple

So if you need to have more than 7 elements in a tuple, you can use the eighth placeholder as a nested tuple. To access its element, you have a property named Rest, which further contains the elements of the nested tuple as Item1, Item2 etc. See the code below:

Tuples in C#

So this was about the concept of tuples. Hope it helps you. Happy coding…!!!

Posted in C# | Tagged | Leave a comment