尽管这类问题被问了很多次,但我还是很难理解存储库和工作单元模式之间的关系.基本上我仍然不明白哪个部分会保存/提交数据更改 - 存储库还是工作单元?
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?
因为我见过的每个例子都与将这些与数据库/OR 映射器结合使用有关,所以让我们举一个更有趣的例子 - 让数据持久化到数据文件中的文件系统;根据模式,我应该能够做到这一点,因为数据的去向无关紧要.
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.
对于基本实体:
public class Account { public int Id { get; set; } public string Name { get; set; } }我想将使用以下接口:
public interface IAccountRepository { Account Get(int id); void Add(Account account); void Update(Account account); void Remove(Account account); } public interface IUnitOfWork { void Save(); }而且我认为就使用而言,它看起来像这样:
And I think in terms of usage it would look like this:
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();记住所有数据都将持久化到文件中,实际添加/更新/删除这些数据的逻辑在哪里?
Bearing in mind that all data will be persisted to files, where does the logic go to actually add/update/remove this data?
Repository 可以在没有 Unit Of Work 的情况下工作,所以它也可以有 Save 方法.
Repository can work without Unit Of Work, so it can also have Save method.
public interface IRepository<T> { T Get(int id); void Add(T entity); void Update(T entity); void Remove(T entity); void Save(); }当您有多个存储库(可能有不同的数据上下文)时使用工作单元.它会跟踪事务中的所有更改,直到您调用 Commit 方法将所有更改持久化到数据库(在本例中为文件).
Unit Of Work is used when you have multiple repositories (may have different data context). It keeps track of all changes in a transaction until you call Commit method to persist all changes to database(file in this case).
因此,当您在 Repository 中调用 Add/Update/Remove 时,它只会更改实体的状态,将其标记为已添加、已删除或已删除...当您调用 Commit、Unit 时Of Work 将遍历存储库并执行实际的持久化:
So, when you call Add/Update/Remove in the Repository, it only changes the status of the entity, mark it as Added, Removed or Dirty... When you call Commit, Unit Of Work will loop through repositories and perform actual persistence:
如果存储库共享相同的数据上下文,工作单元可以直接使用数据上下文以获得更高的性能(在这种情况下打开和写入文件).
If repositories share the same data context, the Unit Of Work can work directly with the data context for higher performance(open and write file in this case).
如果存储库有不同的数据上下文(不同的数据库或文件),工作单元将在同一个 TransactionScope 中调用每个存储库的 Save 方法.
If repositories have different data context(different databases or files), the Unit Of Work will call each repository's Save method in a same TransactionScope.
更多推荐
存储库和工作单元模式
发布评论