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