title: architecture layering and unit of work pattern
body: <p>I am trying to figure out a good practice to architecture / layering and unit of work.</p>
  
  <p>We use C#, write MVC front end apps.  Normal structure at the moment is:</p>
  
  <p>MVC
  Service / Domain Layer
  Repository Layer
  EF6</p>
  
  <p>MVC would simply call the service, (no logic here).  The Service contains all domain logic.  The repository deals with data access, using EF6.  The main three reasons for having a repository layer on top of EF are:</p>
  
  <p>1) Single responsibility (SRP), the service deals with what the business cares about, the repository deals with getting and saving the data.  Using the repository means they are not mingled into the same method.
  2) Testing, it makes it easier to moq the repository. (I am aware that you can now mock the dbcontext, in all honesty have not tried this method yet).
  3) abstracting out EF from the domain as it doesnt really care about it, (this is a very weak arguement though).</p>
  
  <p>We would have individual services and repositories for different parts of the system, such as :</p>
  
  <p>1) CustomerService
   2) InvoiceService
   3) OrdersService</p>
  
  <p>Each repository would have its own impelementation (i.e. no generic repository), allowing us to edit exactly what we want and create queries that return what we want, rather than getting very large objects or making lots of individual calls, (and avoiding having to pass in lots of include statemetnts from the domain).</p>
  
  <p>This structure works well in general.  We find out service layer classes sometimes end up very large (end up breaking SRP).  Think we should end up spliting them into sub services.  If it was CustomerService, maybe it would become CustomerQueryService and CustomerAdminService.  We also find that this structure helps with the repository as some of our queries end up being pretty large transforming the data into the correct format and not pulling out LOTS more data than required.</p>
  
  <p>Where it falls down for me is when you want to use transactions.  This could still work if I turned each repository into a unit of work repository (I think).  The problem occurs when you need to do something that cuts across two or more services.  For example creating an order might want to also call the invoice service to create an invoice.  But if for some reason if the second part failed you would want to roll back the order as well and return a useful error to the client.</p>
  
  <p>I am not sure how to implement this, or if this is structure is a bad idea.  How would I go about setting up a unit of work pattern that allows for mutliple services and repositories (seperation of convcerns and SRP)?</p>