title: Repository and Unit of Work patterns - How to save changes
body: <p>I'm struggling to understand the relationship between the Repository and Unit of Work patterns despite this kind of question being asked so many times. Essentially I still don't understand which part would save/commit data changes - the repository or the unit of work?</p>
  
  <p>Since every example I've seen relates to using these in conjunction with a database/OR mapper let's make a more interesting example - lets persist the data to the file system in data files; according to the patterns I should be able to do this because where the data goes is irrelevant.</p>
  
  <p>So for a basic entity:</p>
  
  <pre><code>public class Account
  {
      public int Id { get; set; }
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I imagine the following interfaces would be used:</p>
  
  <pre><code>public interface IAccountRepository
  {
       Account Get(int id);
       void Add(Account account);
       void Update(Account account);
       void Remove(Account account);
  }
  
  public interface IUnitOfWork
  {
      void Save();
  }
  </code></pre>
  
  <p>And I think in terms of usage it would look like this:</p>
  
  <pre><code>IUnitOfWork unitOfWork = // Create concrete implementation here
  IAccountRepository repository = // Create concrete implementation here
  
  // Add a new account
  Account account = new Account() { Name = "Test" };
  repository.Add(account);
  
  // Commit changes
  unitOfWork.Save();
  </code></pre>
  
  <p>Bearing in mind that all data will be persisted to files, where does the logic go to actually add/update/remove this data?</p>
  
  <ol>
  <li>Does it go in the repository via the <code>Add()</code>, <code>Update()</code> and <code>Remove()</code> methods? It sounds logical to me to have all the code which reads/writes files in one place, but then what is the point of the <code>IUnitOfWork</code> interface?</li>
  <li>Does it go in the <code>IUnitOfWork</code> implementation, which for this scenario would also be responsible for data change tracking too? To me this would suggest that the repository can read files while the unit of work has to write files but that the logic is now split into two places.</li>
  </ol>