0

I'm working with ASP.NET Core MVC from some time and I'm facing a huge problem with organazing my code in the service layer. In some applications the services are used in each other(which according to me can cause circular dependency problems), but in others, services inject just the db context and nothing else(which I think is better, because it follows the separation of concerns principal). Also another problem is when an action should do multiple operations, for example save an internship for a group and then assign all current group members to this internship. If the logic is separated to InternshipService and GroupService and they are called in some action of the InternshipsController like this:

  this.internshipService.Add(someInternshipDto);
  var members = this.groupService.GetAllMembers();
  this.internshipService.AssignGroupMembers(members);

If AssignGroupMembers for some reason fail, we will have inconsistant data in our database. One solution of the problem is just to move all the logic in the InternshipsService, do all the operations I need and finally call SaveChanges(), but this will break the separation of concerns principal.

I'm quite confused with this, so please tell me, what are the things you make in order to solve these problems!

zhelyazko
  • 57
  • 1
  • 7

1 Answers1

0

I think you are mixing the concerns of (1) business logic and (2) data persistence. You can have a service to handle the logic, and a generic repository (i.e. a DbContext) to handle data.

For example:

this.repository.Add<Internship>(someInternshipDto); // data
var members = this.repository.GetAll<Member>(); // data
this.service.AssignGroupMembers(members); // logic
this.repository.SaveChanges(); // data
crgolden
  • 4,332
  • 1
  • 22
  • 40