Implementing Repository Pattern And Dependency Injection In ADO.NET Using Generics In C#

Nowadays, I am trying to learn different design patterns in an object-oriented paradigm that is pretty useful to implement generic solutions for different scenarios. A few weeks ago for a job hunt, I got an assignment to develop a web application that would interact with the database, so I took it up as a challenge and decided to make it loosely coupled using design patterns that were applicable in that scenario.
 
One of them which is implemented in my assignment is a repository pattern using generics and with that Dependency Injection using which I injected dependencies of Repository class via constructor.
 
I made a generic class which would be inherited by other types against the different tables in the application. In this class, I have used different framework features like Reflection and Generics.
 
My generic class is an abstract class, so it needs to be inherited for making use of it. You will see next how we will use it.
 
Here is the Repository class:
  1. public abstract class Repository < tentity > where TEntity: new() {  
  2.     DbContext _context;  
  3.   
  4.     public Repository(DbContext context) {  
  5.         _context = context;  
  6.     }  
  7.   
  8.     protected DbContext Context {  
  9.         get {  
  10.             return this._context;  
  11.         }  
  12.     }  
  13.   
  14.     protected IEnumerable < tentity > ToList(IDbCommand command) {  
  15.         using(var record = command.ExecuteReader()) {  
  16.             List < tentity > items = new List < tentity > ();  
  17.             while (record.Read()) {  
  18.                 items.Add(Map < tentity > (record));  
  19.             }  
  20.             return items;  
  21.         }  
  22.     }  
  23.   
  24.     protected TEntity Map < tentity > (IDataRecord record) {  
  25.         var objT = Activator.CreateInstance < tentity > ();  
  26.         foreach(var property in typeof(TEntity).GetProperties()) {  
  27.             if (record.HasColumn(property.Name) && !record.IsDBNull(record.GetOrdinal(property.Name)))  
  28.                 property.SetValue(objT, record[property.Name]);  
  29.         }  
  30.         return objT;  
  31.     }  

    Now, I have a table in database User whose schema is:
    1. CREATE TABLE [dbo].[tblUser] (  
    2.     [UserID]    INT           IDENTITY (1, 1) NOT NULL,  
    3.     [FirstName] NVARCHAR (25) NULL,  
    4.     [LastName]  NVARCHAR (25) NULL,  
    5.     [UserName]  NVARCHAR (25) NULL,  
    6.     [Password]  NVARCHAR (25) NULL,  
    7.     [IsActive]  BIT           NULL,  
    8.     [IsDeleted] BIT           NULL,  
    9.     [CreatedBy] INT           NULL,  
    10.     [CreatedAt] DATETIME      NULL,  
    11.     [UpdatedBy] INT           NULL,  
    12.     [UpdatedAt] DATETIME      NULL,  
    13.     [Email]     NVARCHAR (50) NULL,  
    14.     PRIMARY KEY CLUSTERED ([UserID] ASC)  
    15. );  
    Against this table, I have a Model class for mapping from table to that type which looks like the following,
    1. public class User {  
    2.     public int UserID { get;  
    3.         set; }  
    4.     public string FirstName { get;  
    5.         set; }  
    6.     public string LastName { get;  
    7.         set; }  
    8.     public string UserName { get;  
    9.         set; }  
    10.     public string Password { get;  
    11.         set; }  
    12.     public bool IsActive { get;  
    13.         set; }  
    14.     public bool IsDeleted { get;  
    15.         set; }  
    16.     public DateTime CreatedAt { get;  
    17.         set; }  
    18.     public int CreatedBy { get;  
    19.         set; }  
    20.     public DateTime UpdatedAt { get;  
    21.         set; }  
    22.     public int UpdatedBy { get;  
    23.         set; }  
    24.     public string Email { get;  
    25.         set; }  

      We want to fetch data from the User table for which we will create a Repository class for User type and then we will write implementation to fetch records from the User table from the database. All our methods that need to get data, insert data, update data, or delete data from the User table will reside in the UserRepository class.
       
      Here is the implementation of User Repository class:
      1. public class UserRepository: Repository {  
      2.     private DbContext _context;  
      3.     public UserRepository(DbContext context): base(context) {  
      4.         _context = context;  
      5.     }  
      6.   
      7.     public IList GetUsers() {  
      8.         using(var command = _context.CreateCommand()) {  
      9.             command.CommandText = "exec [dbo].[uspGetUsers]";  
      10.             return this.ToList(command).ToList();  
      11.         }  
      12.     }  
      13.   
      14.     public User CreateUser(User user) {  
      15.         using(var command = _context.CreateCommand()) {  
      16.             command.CommandType = CommandType.StoredProcedure;  
      17.             command.CommandText = "uspSignUp";  
      18.             command.Parameters.Add(command.CreateParameter("@pFirstName", user.FirstName));  
      19.             command.Parameters.Add(command.CreateParameter("@pLastName", user.LastName));  
      20.             command.Parameters.Add(command.CreateParameter("@pUserName", user.UserName));  
      21.             command.Parameters.Add(command.CreateParameter("@pPassword", user.Password));  
      22.             command.Parameters.Add(command.CreateParameter("@pEmail", user.Email));  
      23.             return this.ToList(command).FirstOrDefault();  
      24.         }  
      25.     }  
      26.   
      27.     public User LoginUser(string id, string password) {  
      28.         using(var command = _context.CreateCommand()) {  
      29.             command.CommandType = CommandType.StoredProcedure;  
      30.             command.CommandText = "uspSignIn";  
      31.             command.Parameters.Add(command.CreateParameter("@pId", id));  
      32.             command.Parameters.Add(command.CreateParameter("@pPassword", password));  
      33.             return this.ToList(command).FirstOrDefault();  
      34.         }  
      35.     }  
      36.   
      37.     public User GetUserByUsernameOrEmail(string username, string email) {  
      38.         using(var command = _context.CreateCommand()) {  
      39.             command.CommandType = CommandType.StoredProcedure;  
      40.             command.CommandText = "uspGetUserByUsernameOrEmail";  
      41.             command.Parameters.Add(command.CreateParameter("@pUsername", username));  
      42.             command.Parameters.Add(command.CreateParameter("@pEmail", email));  
      43.             return this.ToList(command).FirstOrDefault();  
      44.         }  
      45.     }  

        We are done for the UserRepository for now, I have added methods and wrote a Stored Procedure to complete the assignment. Now, I will tell you how to make use of it in the Service Layer or in Business Rule to do operations.
         
        Firstly, create an interface named IUserService:
        1. [ServiceContract]  
        2. public interface IUserService  
        3. {  
        4.     [OperationContract]  
        5.     IList GetUsers();  
        6.   
        7.     [OperationContract]  
        8.     User RegisterUser(User user);  
        9.   
        10.     [OperationContract]  
        11.     User Login(string id, string password);  
        12.   
        13.     [OperationContract]  
        14.     bool UserNameExists(string username, string email);  
        15. }  
        Here is my WCF Service for user that calls the UserRepository for doing operations,
        1. public class UserService: IUserService {  
        2.     private IConnectionFactory connectionFactory;  
        3.     public IList < user > GetUsers() {  
        4.         connectionFactory = ConnectionHelper.GetConnection();  
        5.         var context = new DbContext(connectionFactory);  
        6.         var userRep = new UserRepository(context);  
        7.         return userRep.GetUsers();  
        8.     }  
        9.   
        10.     public User RegisterUser(User user) {  
        11.         connectionFactory = ConnectionHelper.GetConnection();  
        12.         var context = new DbContext(connectionFactory);  
        13.         var userRep = new UserRepository(context);  
        14.         return userRep.CreateUser(user);  
        15.     }  
        16.   
        17.     public User Login(string id, string password) {  
        18.         connectionFactory = ConnectionHelper.GetConnection();  
        19.         var context = new DbContext(connectionFactory);  
        20.         var userRep = new UserRepository(context);  
        21.         return userRep.LoginUser(id, password);  
        22.     }  
        23.   
        24.     public bool UserNameExists(string username, string email) {  
        25.         connectionFactory = ConnectionHelper.GetConnection();  
        26.         var context = new DbContext(connectionFactory);  
        27.         var userRep = new UserRepository(context);  
        28.         var user = userRep.GetUserByUsernameOrEmail(username, email);  
        29.         return !(user != null && user.UserID > 0);  
        30.     }  

          You can see that when creating an instance of UserRepository, I am injecting database context via the constructor and then I am calling different methods from userRepository according to need.
           
          Now in the future, when I add another table in the database, I will create another Repository type and implement its Data Access logic and will call it in the same way, so applying Dependency Injection and Repository pattern, we are following DRY principle to some extent, but I am sure we can make it better than this.


          Similar Articles