Implementing Repository Pattern Along With Dependency Injection

What is repository pattern?

Repository pattern is a design pattern useful to solve the problem of tight coupling between application layer and database layer. By using repository pattern, we are not using concrete database class objects to perform CRUD operation.

So tight coupling means?

In the above diagram you can see object of employee class from database layer is created in business layer and then using that object GetEmployeeDetails() method is called to get data from database.

As per application design practice we should not use “New” keyword to access methods of the Employee class object.

So how to access "GetEmployeeDetails()" method without creating object of a class?

Here comes the role of repository pattern and dependency injection. We can use interface instead of class to access method.

 Below screenshot is showing final output of the article using repository pattern.

Step 1

Add an IRepository interface in database layer as shown in below screenshot.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess {
    public interface IRepository {
        DataTable GetEmployeeDetails();
    }
}

Step 2

Add EmployeeRepository.cs class and implement IRepository interface

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess {
    public class EmployeeRepository: IRepository {
        public DataTable GetEmployeeDetails() {
            DataTable dt = SqlHelper.ExecuteProc("GetEmployeeDetails");
            return dt;
        }
    }
}

Step 3

Add reference to “Unity.Mvc” and “Newtonsoft.Json” in your MVC project using "Manage Nuget package" option.

"Unity.Mvc" – is for dependency Injection

"Newtonsoft.Json" – is for converting data table in JSON string format.

Step 4

After adding reference in step 3, under “App_start” folder you can find UnityConfig.cs file. In this file you need to register your Interface and class which implement that Interface.

Step 5

Now in employee controller constructor we can Inject interface “IRepository” and then we are accessing GetEmployeeDetails() method without using “New” keyword.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RepoPattern.Models;
using DataAccess;
using System.Data;
using Newtonsoft.Json;
namespace RepoPattern.Controllers {
    public class EmployeeController: Controller {
        // GET: Employee
        private readonly IRepository _repo = null;
        public EmployeeController() {}
        public EmployeeController(IRepository empRepo) {
            _repo = empRepo;
        }
        public ActionResult Index() {
            return View();
        }
        public string GetEmployeeDetails() {
            DataTable dt = _repo.GetEmployeeDetails();
            string json = JsonConvert.SerializeObject(dt, Formatting.None);
            return json;
        }
    }
}

Step 6

Calling Employee Controller action using Ajax call. Under Employee view.

@{
    ViewBag.Title = "Employee Details";
}
<h2>Employee Details</h2>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnLoadEmp").click(function () {

            EmployeeDetailsAjaxCall();
        });
    });
</script>
<div><button id="btnLoadEmp" title="Load Employee Data">Load All Employee Data</button></div>
<div style="width:100%;padding:50px">
    <table class="table" id="tblEmployee" style="width:100%"></table>
</div>

Step 7

In CallAjax.Js file

function EmployeeDetailsAjaxCall() {
    try {
        $.ajax({
            async: true,
            url: "/Employee/GetEmployeeDetails",
            type: "GET",
            success: function(result) {
                if (result != "") {
                    LoadEmployee(result);
                }
            }
        });
    } catch (ex) {}
}

function LoadEmployee(result) {
    $("#tblEmployee").empty();
    var firstRow = "<tr><td>Employee Id</td><td>First Name</td><td>Last Name</td></tr>";
    $("#tblEmployee").append(firstRow);
    try {
        var responseObject = JSON.parse(result);
        for (itm = 0; itm < responseObject.length; itm++) {
            var EmpId = responseObject[itm]["EmployeeID"];
            var FirstName = responseObject[itm]["FirstName"];
            var LastName = responseObject[itm]["LastName"];
            var rows = "<tr>" + "<td>" + EmpId + "</td>" + "<td>" + FirstName + "</td>" + "<td>" + LastName + "</td>" + "</tr>"
            $("#tblEmployee").append(rows);
        }
    } catch (ex) {}
}

 


Similar Articles