2. Agenda
Quick Intro
Role of a MVC/Web-API Controller
Controllers – the old fashioned way
Demo
Controllers – the old fashioned way
Controllers – the new way
Introducing Repository
Demos
Basic Repository
Controllers – the new way
Generic Repository Demo
Unit Of Work Demo (if time permits)
Question/Comments
4. Role of a MVC/Web-API Controller
A Controller (MVC or Web-API) typically:
Receives requests from a user. The request might contain data that user want to
read/add/update/delete
Process the request using the data received by performing CRUD operations against a
database
Returns data, if applicable, to the user
Controller might depend upon Helper Classes and/or BLL/DAL for validating the
data and updating data in the database
5. Controllers – the old fashioned way
Controller initiates a DB-Context
Methods within a controller uses the DB-Context to perform CRUD operations,
resulting in:
Controller being tightly coupled with the ORM technology (e.g. Entity Framework) being
used
Controller might depend upon BLL and DAL for validating the business logic and
updating data in the database instead of directly using DB-Context
Now, DAL is tightly coupled with the ORM technology being used
7. Controllers – the new way
Controllers (or underlying DAL or Helper Classes) should not depend on ORM
Technology and/or instantiate a DB-Context, instead should uses Repository
Controllers should only have to deal with Primitive values, POCOs or Collection of
POCOs
If ORM Technology is changed Controller or DAL should not be required to be
refactored
Advantages
DB technology change are unaffected in the Core application logic
Unit testability (by creating Mock objects)
Team member with different expertise can work together and as long as the Interface
“contract” is not broken. The “back-end” team member can completely change how data is
stored/retrieved e.g. From SQL DB to NoSQL DB to WebService to WebAPI without affecting
work done by “front-end” developers
8. Introducing Repository
Build an Interface and related concrete Implementation class that contain various methods that
performs CRUD operations
These methods expects and returns Primitive values (e.g. integer for Keys), POCOs or collections of
POCOs as parameters and values respectively
Method should take primitive types and/or Model Object as parameters and return primitive values,
Model Object and/or void (for action operation)
Recommendation: a separate Repository for each entity (DB object)
** If you need to call a Stored Procedure create a method in the repository **
In controller use Interface to perform CRUD operations
Using dependency injection a Concrete Implementation of class can be passed at runtime
Mock Implementation class of Repository can be passed by a Unit Test
Concrete implementation of the Repository will use DB-Context to perform CRUD operation as
dictated by the method – is only object that would be tightly coupled