Alex Rivera | Logout

Difference between Repository and Service Layer?

Asked 2011-02-19T06:51:14.833
238

In OOP Design Patterns, what is the difference between the Repository Pattern and a Service Layer?

I am working on an ASP.NET MVC 3 app, and am trying to understand these design patterns, but my brain is just not getting it...yet!!

Edit
Report

1 Answer

378

Repository Layer gives you additional level of abstraction over data access. Instead of writing

var context = new DatabaseContext();
return CreateObjectQuery<Type>().Where(t => t.ID == param).First();

to get a single item from database, you use repository interface

public interface IRepository<T>
{
    IQueryable<T> List();
    bool Create(T item);
    bool Delete(int id);
    T Get(int id);
    bool SaveChanges();
}

and call Get(id). Repository layer exposes basic CRUD operations.

Service layer exposes business logic, which uses repository. Example service could look like:

public interface IUserService
{
    User GetByUserName(string userName);
    string GetUserNameByEmail(string email);
    bool EditBasicUserData(User user);
    User GetUserByID(int id);
    bool DeleteUser(int id);
    IQueryable<User> ListUsers();
    bool ChangePassword(string userName, string newPassword);
    bool SendPasswordReminder(string userName);
    bool RegisterNewUser(RegisterNewUserModel model);
}

While List() method of repository returns all users, ListUsers() of IUserService could return only ones, user has access to.

In ASP.NET MVC + EF + SQL SERVER, I have this flow of communication:

Views <- Controllers -> Service layer -> Repository layer -> EF -> SQL Server

Service layer -> Repository layer -> EF This part operates on models.

Views <- Controllers -> Service layer This part operates on view models.

EDIT:

Example of flow for /Orders/ByClient/5 (we want to see order for specific client):

public class OrderController
{
    private IOrderService _orderService;

    public OrderController(IOrderService orderService)
answered 2011-02-19T07:16:45.983

Your Answer