views:

62

answers:

2

If a service uses repositories to persist data, shouldn't it be in a repository?

+2  A: 

Well, I think the answer is pretty subjective based on your problem domain and the general architecture you select. But, fwiw, here is my approach:

Repositories provide a unified view of the storage containers of objects.

Services provide functionalty that in many cases use repositories.

Let's take an example: we have a shopping cart application and it needs to know

  1. how to save orders
  2. how to add payments to orders in a variety of currecies
  3. List item how to find the current exchnage rate for a given currency.

One structure for this might be.

CurrencyRatesRepository
  AddCurrency( "US$" )
  AddCurrency( "EUR" )
  AddEffectiveeRate( "US$", "EUR", 2009/01/01 14:00:00:00.000, 1.5 )


CurrencyService
  rate = GetEffectiveRate( "US$", "EUR" );

ShoppingCartRepositroy
  SaveOrder( orderid=1, "Pair of Shoes", EUR99.99 );
  AddPayment( orderid, "US$", 150 );

Now, the AddPayment method on the ShoppingCart repository can invoike GetEffectiveRate on the currencyserve to compute the curent value of the US$150 in Euro.

The obvious questionis. why bother with the service at all why not just add the GeteffectiveRate method to the currency repository. Well, the answer is - to decouple your shopping cart business logic from the currency repositiory. This would allow you to change currency repositoryies at a later date.

Anyway, as I say, wether you call something a service or a repository is pretty subjective. But in general I think of a Service as a higher level abstration that provides additional logic and functionalty layered over a repository.

Hope that helps.

thrag
I know the answer was pretty subjective, but you did give me the answer I was searching for and I thought about it the same way. I also wondered why bothering with a service and not just add everything to repositories. Especially, when someone uses my API, it can be difficult to find some logic if it's subjective whether to put it in service or repo...one person will look for it in repo, another one in service... Thx for the answer.
Lieven Cardoen
+1  A: 

I believe Evans' first couple of paragraphs on the subject is pretty clear.

A service is used to place logic that doesn't naturally fit in any specific Domain object. It doesn't matter whether your service uses repositories or not - it's the behavioural logic that defines the service.

Unfortunately Service is an overloaded term - it can be easy to get 'Web Services' and 'Domain Services' mixed up.

Vijay Patel