Working With Repository Pattern in WebAPI 2

Introduction

In this article we will learn the next topic for the Web API 2, the Repository Pattern. In this article I will deal with the Repository Pattern in the Web API and describe the debugging process. In general the definition of a repository is "A place, room, or container where something is deposited or stored", according to Merrriam-Webster. The Repository Pattern is a common construct to avoid duplications of data access logic throughout our application. This includes direct access to a database. The purpose of a repository is to hide the details of accessing the data from the database or any other resource. In this approach we can easily query the repository data objects, without having to know how to provide things like connection strings. The repository behaves like an in-memory data collection to which we can add, delete and update objects.

RepositoryDiagram

Let us try to understand the Repository Pattern using code. 

Prerequisites

There are the following things we need to use when developing a Web API application:

  • Visual Studio 2013
  • ASP.NET Web API

Getting Started

Step 1

Open Visual Studio 2013.  As in the following image we need to open Visual Studio 2013 and select "File" -> "New" -> "Project...".



Step 2

Select New Project and provide a nice name to your application and choose the Web API Template.


Step 3

Add a Student class inside the Model.

AddingNewEmployeeClass

Step 4

Add an interface as the repository class inside the model as in the following:

  1. namespace WebApiWithRepository.Models  
  2. {  
  3.     interface IStudentRepository  
  4.     {  
  5.         IEnumerable<Student> GetAll();  
  6.         Student GetById(int id);  
  7.     }  
  8. }  

Step 5

Implement the Interface as in the following:

  1. namespace WebApiWithRepository.Models  
  2. {  
  3.     public class StudentRepository : IStudentRepository  
  4.     {  
  5.         private List<Student> student = new List<Student>  
  6.         {  
  7.          
  8.             new Student { StudentId = 1, Studentname = "rajeev", StudentAddress = "Noida" },  
  9.             new Student { StudentId = 2, Studentname = "rohit", StudentAddress = "Pune" },  
  10.             new Student { StudentId = 3, Studentname = "Manish", StudentAddress = "Mumbai" },  
  11.             new Student { StudentId = 4, Studentname = "Mohit", StudentAddress = "Delhi" },  
  12.             new Student { StudentId = 5, Studentname = "Rajeev Ranjan", StudentAddress = "Hazaribagh" }  
  13.     };  
  14.   
  15.         public IEnumerable<Student> GetAll()  
  16.         {  
  17.             return student;  
  18.         }  
  19.         public Student GetById(int id)  
  20.         {  
  21.             return student.Find(x => x.StudentId == id);  
  22.         }  
  23.     }  
  24.         
  25. }  

Step 6

Add a controller.AddingNewController

In the coding part, when we start to write, we need to add some important references of Models and implement two methods.

Step 7

Build the application and check the output from Postman.

SelectAllStudentsList

And now we can see the same output in the specific id basis.
 
SelectById 

Now we will learn the process of debugging. Before beginning to learn debugging let's try to understand how the Routing Mechanism works in the Web API. The following diagram depicts the real image of routing in the web API. Let's understand it.

RoutingDebugging

Routing is the main mechanism of the ASP.NET Web API that is composed of the following three steps:

  • Find the matching route and parse the route data
  • Find the matching controller
  • Find the matching action

Since the preceding steps fails, the API will not be executed. For example, suppose no controller is found, then the matching ends and no action is seen by the RouteTable and gets an error.

  • The first point is as said above; a route will be matched. Every route is defined with a route template, defaults, constraints, data tokens and handler. (Routes are configured by default in App_Start\WebApiConfig.cs ) Once a route is matched, the request URL is parsed into the route data based on the route template. Route data is a dictionary mapping from string to object.
  • Controller matching is purely done based on the value of the “controller” key in the route data. If the key “controller” doesn't exist in the route data, the controller selection will fail.

  • If the route data contains the key “action” then the action will be searched based on the action name. Unlike ASP.NET MVC, the Web API routes generally do not use action names in routing.

    Find all actions where the action name is “action” in the route data.

    Each action supports one or more HTTP Verbs (GET, POST, PUT and so on). Eliminate those actions that don't support the current HTTP request's verb.

If the route data doesn't contain a key “action”, then the action will be searched based on the supported request method directly. Selected actions in either of the preceding two steps, examine the parameters of the action method. Eliminate those actions that don't match all the parameters in the route data.

There are some circumstances where we can find some error, something like if all actions that are marked by the NonAction attribute.

If more than one action matches, an HTTP 500 error is thrown. (Internally an HttpResponseException is thrown.)

If there is no matching action, an HTTP 404 error is thrown.


Similar Articles