Leandro Soares
Leandro Soares

Reputation: 2972

MVC - Best pattern (UoW + Repositories + Services + DI)

I've been doing mvc for some time, but it's my first contact with DI.

I started a new project with Ninject which seems pretty simple and easy to understand, however almost every tutorial I saw has UoW, Repositories and Services.

What I understand is that:

Ok, it took me some time to "eat" the Repository thing since i prefer to pass the EF Context trough the UoW.

Is it ok if i forget the Repository and just use the context? Or is it used for any Unit Test task?

What's the Service's usage? Since I may perform every actions/tasks inside UoW and then call it inside the controllers.

Is there any better set of patterns to use?

Upvotes: 1

Views: 514

Answers (2)

Gabriel Ferrarini
Gabriel Ferrarini

Reputation: 961

Since these are very common and you might be talking about either, I'm going to give a brief explanation about each.

Domain Services: When you have an entity and you start to push logic into it, you might get to a point where part of the logic doesn't really belong to that entity, so you create a Domain Service to abstract this logic away. An example would be:

public class Shipment
{
    ...
    public void CalculateFee(IFeeCalculatorService feeCalculatorService)
    {
        ... Any additional and entity relevant logic for fee calculation can be here as well.
        this.Fee = feeCalculatorService.Calculate();
    }
    ...
}

Application Services: These are the services that you will be calling from your controllers to encapsulate the operations needed for a specific task. Let's say you have a controller to receive a friendship request approval or rejection. Your Application Service should receive enough data to be able to:

  • Find the friendship request domain entity
  • Call its approve or reject method
  • Call the methods to persist that change back to the database
  • Return relevant information to the controller

Infrastructure Services: These services will abstract the logic that is not related to the business, but related to how the application works. An example would be a service to validate security tokens received on your requests, or to perform logging activities.

Upvotes: 2

Mattias Åslund
Mattias Åslund

Reputation: 3907

EFs DBContext already implements both the UoW and Repository patterns, so yiu have no benefit of implementing those again in yiur own code.

Services are a way to abstract business logic so it can be reused

Upvotes: 1

Related Questions