[X]

C# Repository Pattern - Design Patterns in Action

Repository Pattern

Repository pattern is one of the pattern which is most frequently used in Data access layer. This provides an abstraction to underlying database. This is also useful when database is not ready and we want to test the application by building an stub.

So repository pattern provides testability, abstration and  dependency injection.

Repository

Repository is defined as "an abstraction that provides us with persistence ignorance and a separation of concerns where the responsibility of persisting domain objects is encapsulated by the Repository that  leaving the domain objects to deal entirely with the domain model and domain logic."

I am going to show a sample of repository pattern implementation with c# and entity framework. Our entity framework DataContext object will be inside the constructor of the repository class. This will implement IDisposable interface to make sure that object is disposed properly in case of any failure or when object is no more required.

We will delcare some of the most frequenlty used operations in interface such as GetOne, GetMany, Filter, Save, Delete.

So IRepository and RepositoryImplementation Class will be the building blocks of repository pattern.

Creating IRepository Class:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace BnF.DataAccess
{
    interface IPanelRepository<T>
    {
        T GetPanelByID(int panelID);
        List<T> GetPanels();
        List<category> GetPanelCategories(int panelID);
        IQueryable<T> Filter(Expression<Func<T, bool>> filter);
        void Save(T entity);
        void Delete(T entity);
    }
}

 

 

Creating RepositoryImplementation Class:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace BnF.DataAccess
{
    public class PanelRepository:IPanelRepository<panel>
    {
        BnFDBEntities _context;
        public PanelRepository()
        {
            _context = Database.EntityContext;
        }

        public List<panel> GetPanels()
        {
            return _context.panels.Where(p => p.isActive == true).ToList<panel>();
        }

        public List<category> GetPanelCategories(int panelID)
        {
            return (from c in _context.categories
                    join pc in _context.panel_categories on c.idCat equals pc.categoryId
                    where pc.panelId==panelID && c.active==-1
                    orderby c.displayOrder
                    select c
                    ).ToList<category>();
        }

        public panel GetPanelByID(int panelID)
        {
            return _context.panels.Where(p => p.panelId == panelID).FirstOrDefault();
        }

        public void Save(panel p)
        {
            //not implemented
        }

        public void Delete(panel p)
        {

        }

        public IQueryable<panel> Filter(Expression<Func<panel, bool>> filter)
        {
            return _context.panels.Where(filter);
        }

    }
}

 

 

You can see above there is one more class "Database". Here this class is very important as it is maintaining the singleton instance of DatabaseContext object.

This singleton pattern is one of the variation which is achieved using Per Session Per Request Context.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace BnF.DataAccess
{
    public class Database
    {
        public static BnFDBEntities EntityContext
        {
            get
            {
                if (HttpContext.Current != null && HttpContext.Current.Items["BnFDBEntities"] == null)
                {
                    HttpContext.Current.Items["BnFDBEntities"] = new BnFDBEntities();
                }
                return HttpContext.Current.Items["BnFDBEntities"] as BnFDBEntities;
            }
            set
            {
                if (HttpContext.Current != null)       
                    HttpContext.Current.Items["BnFDBEntities"] = value;
            }
        }
    }
}

 

 

Also please note that "BnFDBEntities" is the ObjectContext which was generated when we added the EntityModel to our project.

Above is the one of the way of implementing "Repository Pattern" and "Singleton Pattern". There are lots of variation to above patterns.

blog comments powered by Disqus

Posts By Month