1

is itIa good coding standard to allow ASP.NET MVC controller actions to access a repository directly (even though a service layer is present for the heavy lifting, e.g. LoginService.Authorize() ) to retrieve, add, or update data? Or should everything go through the service, and from there to the repository?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Alex
  • 75,813
  • 86
  • 255
  • 348

4 Answers4

4

For smaller applications/webs, i tend not to use service layer, because it just maps Repositories methods 1:1, and I loose KISS. But in the end, it depends on business model; repository abstracts db access, and services encapsulates logic.

Hrvoje Hudo
  • 8,994
  • 5
  • 33
  • 42
2

It's better to go through the service layer (depending on how you've implemented it though), because that's the point of it - to be a single access point, thus any business-specific things you do there, are represented and implemented across all callers.

Noon Silk
  • 54,084
  • 6
  • 88
  • 105
1

It really depends on the complexity. If you're dealing with any transcation scoping, I'd definitely decouple that away from the controller into your service layer.

RailRhoad
  • 2,128
  • 2
  • 25
  • 39
1

In my opinion it will depends on your design/architecture. What's the purpose of a repository ? Do CRUD operations (Create, Read, Update and Delete).

If you're using the anemic domain models in a classic three-tiers architecture all logic applied to the models are made in the services. In this case the choice is obvious : You shouldn't call the repository directly. Why ? Since your models are silly and the logic is in the services you could create invalid models. If you can call the repository you could create/update an invalid model in database. If you call the services it should be able to correct or fill your model before create/update it.

If you're using a rich domain model in an onion architecture it's different. Since your models are supposed to be always valid (when you create one from the constructor or from the factory all validations has been performed and when you update one it's the same thing) you can without any problem call directly the repository. In this context all the logic is in the models directly and the services are just used to stored the logic that doesn't belong to one model specificly.

Now the question is not "how to use repository" but "what design/architecture do I need ?" and the first question will be answered :-)

Arcord
  • 1,724
  • 1
  • 11
  • 16