RSS

Monthly Archives: November 2012

Creating a MVC Application using Unit of Work, Repository Pattern and NinJect

Part 1 – Summary of the Solution (Click Here)

Part 2 – The Solution

In this Post I’ll examine the components that make up the architectural solution described in my previous post in more detail up to the API / Controller level.  If you want a copy of the complete code then don’t hesitate to contact me on the About Section of my blog and I’ll send you a copy.

Ok so let’s start at the bottom with the database.  Well there is no database, not yet anyway.  In my example I have used the Code-first approach which allows me to describe my model in code, from which Entity Framework will construct the database.  Knowing this lets have a look at my model project;

The Solution

I am using the common Blog Model.  Keeping it simple, a Blog can contain many Posts and a Post can contain many Comments.

For this tutorial is not necessarily important to know what properties these objects contain but rather that they will reflect tables within our database and act as container objects to pass information around our system.  However here is the code for the Post Class just so you have an idea of how it is constructed:

The Post Model Object

Remember that Entity Framework has the job of trying to convert C# model classes to the database and so it’s wise to give it as much information as possible to give it a helping hand.  I’ve demonstrated this by adding an annotation to the Title Property and creating references back to Parent objects e.g. BlogId, Blog etc. which can be used by Fluent API (Not shown in this post) to enforce relationships between the data objects.  I have also created the Comments collection as Virtual.  This will ensure that the Entity Framework will not initialise the Comments collection until the data is specifically requested, improving performance.

Once we have our model classes we need to implement the repository layer to provide consistent data access.  To provide the consistent data access I created a new project (to contain my interfaces) which contains an IRepository Interface;

IRepository Class

This provides us with a generic interface which will accept an object from our model project and describe the data access actions that will be available to our application, e.g. retrieving records, updating records and adding a new record etc.  By implementing this interface we have a standard set of actions that can be performed on our database model (consistency).  If a model object needs to extend this set of actions, then we just create another repository interface which implements IRepository and includes the extra method signatures.  For example check out IPostRepository in this example which adds an extra method to return the number of comments associated with a Post;

IPostRepository Class

Following on from this we need to create the concrete implementations of the repository classes.  This is done within another project which is essentially our data layer.  I have created a class named EFRepository which implements IRepository.  This will be our base data access class and every object in our model will implement the functionality within this class as a minimum;

EFRepository Class

We will also need implementations for extended repository interfaces such as the IPostRepository created earlier;

PostRepository Class

As in this instance we are using the Entity Framework, the repositories will access the database via the DBContext. You will notice that in the EFRepository class we create an instance of this DBContext in order to perform operations of the database.  When developing against the Entity Framework using the Code-First approach you must create a Context Class which implements DBContext to identify the data objects which will be made available via the DBContext.  Here is an example of the Context class I created for this project named BlogDBContext;

BlogDbContext Class

By now we have described our model objects and created our repositories to allow us to perform data persistence actions on the database objects that these represent.  The next step is to implement the Unit of Work Pattern.  This requires that we create a Unit of Work class which will provide a single point of access to our repositories and a method to persist changes to the database as a single transaction improving efficiency and reducing concurrency problems.

So what does the Unit of work class look like?  Well if we examine its interface it simply exposes the repository objects and a single method to persist any changes back to the database.  That’s it simple.

IWebTemplateUoW Class

And the concrete implementation of the UnitOfWork class would look like this;

WebTemplateUoW Class

The key things to point out here is that firstly when we invoke the Unit of Work class we also create a new instance of our DBContext.  By wrapping the DBContext within the Unit of Work we can submit our changes within a single update request and dispose of the context once the request is complete.  We also have the advantage of performing atomic transactions, for example if one object fails to update when updating multiples objects within the database then we can rollback all objects to their original state reducing data inconsistency issues.

Another important point is that access to all repositories are available within this class and that also our context can be configured from this class.  If there was suddenly a business requirement to move to another database platform which used different data access technologies e.g. nHiberate, then we could create another Unit of Work class and substitute it for this one without breaking the logic and UI layers.  The advantages of a decoupled system!!

The final stage is to implement the Unit of Work into our business layer or in the case of this post our controllers within our API as I created a MVC application.

A sample controller Class using the Unit of Work

In this example I have created a quick controller class which when instantiated creates an instance of the Unit of work.  This in turn will create an instance of our DBContext and out repository classes. As a result we instantly have available all the objects from our model and the operations associated with that model via the repository interfaces e.g. GetAll(), Remove(entity), Add(newEntity) etc. and in the case of the Post object GetCommentCount() which was implemented via the IPostRepository.

The only bit of code in this controller you might be querying is the constructor which seems to accept an instantiated unit of work object, in this case of type IWebTemplateUoW.  This is because the Unit of Work Object is created for the controller using NinJect. NinJect is a technology which allows dependency injection.  In other words it allows the application to choose which concrete implementation of a component to create at run time.

Dependency Injection and NinJect is a large topic so I won’t try to go into it in any level of detail here but essentially I created a NinJect configuration class which tells my application that if it comes across an object of type IWebTemplateUow, then create an instance of WebTemplateUow.

The Ninject Configuration Class

 

 

 

 

 

 

 

 

 

 

 

 

Creating a MVC Application using Unit of Work, Repository Pattern and NinJect

Part 1 – Summary of the Solution

When developing new Web Applications using ASP.NET MVC we always encounter the same questions; where does the business logic layer fit in?, how can we implement Unit Testing?, what if the database changes? How can we make it scalable?

As a result, I set out to create a project template which could be used for future MVC projects and would address the questions above.

After much investigation the best approach I found was to develop the following framework:

 

Solution Component Overview

In this post I will just give an overview of the main components of the solution which is followed by a more detailed technical post of how the solution is put together.

 

Starting at the bottom of the diagram you will notice I have a database and sitting on top of that database I have the Entity Framework.  In the following post you will see how I use the Code-First approach to allow the Entity Framework to construct the database based on the model.

On top of the Entity Framework I am making use of the Repository Pattern to allow access to the objects that make up the model and to enforce the actions associated with these objects.  By making use of the Repository Pattern we prevent needless duplication of Data Access Logic code and enforce a standard set of actions that can be applied to the data objects e.g. Get All(), Find(), Add, Delete() etc.

The Repositories serve up the Model objects to the Unit of Work.  Using the Unit of Work Pattern we allow the higher tier layers to access and modify the data objects via a single class.  This result is a single Commit (operation / transaction) when writing changes made to multiple objects, back to the database allowing for a much more efficient approach and reducing concurrency issues.  Using the Unit of Work Pattern also means we de-couple the higher logic and UI tiers from the Database context which allows us to substitute in alternative Unit of Work classes that may be used for Unit Testing or connecting to alternative databases.

The Unit Of work object is then directly used by the API components or if required a Business Logic Layer which can be slotted between the API / UI layer and the Unit of Work classes to give a further level of separation.  In my example I have used NinJect as my IoC container to instantiate the correct Unit Of Work Objects but you will see more on this in the following post.

Our UI then has access to our data level objects and models without needing to know any detail about the ins and outs of the system which will allow us to build any UI on top of our API service, whether it’s a desktop, Web, Phone, IPad app etc.

Click here to see my real world template