Accepted answer

One of the main problems in your current approach is that the repositories individually have the responsibility to create/update the entities they hold on the database - This means that if you have changes in one repository and update another repository (i.e. your Create() call) both will be committed to the DB.

The usual way to structure this is having a unit of work (i.e. see here) that sits on top of all repositories that is responsible to commit changes to the DB, this structure also allows for transactions spanning multiple repositories.


I would say you should probably keep the responsibility of the repository to be saving and retrieving data for the entity. The "role" is a bit more on the "business logic" side and I would put that one layer up in a Service so you don't do any business logic responsibilities in the repository. For example you could call it CreateNewUserService and it would take the new users from the repository and then add the role. You would call that directly from the controller passing those arguments that you are applying directly now.

That way if your business logic changes so that you want to intialize the user as something else or not at all, you don't have to rip up the repository as it can keep it's responsibility of providing the user. This keeps the separation of concerns to be more clear as well and helps with maintenance and testability of both the repository and the service.

Related Articles