Repository and Unit of Work patterns - How to save changes

后端 未结 5 1798
旧巷少年郎
旧巷少年郎 2021-01-30 05:28

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\

5条回答
  •  情书的邮戳
    2021-01-30 06:07

    Using the file system can complicate things quite much if you want to do it on yourself.

    Only write when the UoW is committed.

    What you have to do is to let the repositories enqueue all IO operations in the UnitOfWork. Something like:

    public class UserFileRepository : IUserRepository
    {
        public UserFileRepository(IUnitOfWork unitOfWork)
        {
            _enquableUow = unitOfWork as IEnquableUnitOfWork;
            if (_enquableUow == null) throw new NotSupportedException("This repository only works with IEnquableUnitOfWork implementations.");
    
        }
    
        public void Add(User user)
        {
            _uow.Append(() => AppendToFile(user));
        }
    
        public void Uppate(User user)
        {
            _uow.Append(() => ReplaceInFile(user));
        }
    }
    

    By doing so you can get all changes written to the file(s) at the same time.

    The reason that you don't need to do that with DB repositories is that the transaction support is built into the DB. Hence you can tell the DB to start a transaction directly and then just use it to fake a Unit Of Work.

    Transaction support

    Will be complex as you have to be able to roll back changes in the files and also prevent different threads/transactions from accessing the same files during simultaneous transactions.

提交回复
热议问题