.NET Core Difference between TransactionScope and DistributedLock

414 views Asked by At

Good morning everyone,

We are implementing a method that stores a document into SqlServer with EF Core.

This method called SAVE is called by multiple endpoints of the controller and is used both from a createDocument endpoint and another endpoint putDocument.

An extra requirement is that this method contains two calls that store the document and its properties into 2 different repositories, therefore we wanted to achieve that if one of the two calls to the repositories fails, it rolls back the changes.

Moreover, the whole code is hosted on multiple machines that's why we also implemented the library of distributed lock of macallon (GitHub) in order to avoid that the same document is accessed/modified by two different machines at the same time.

Is it correct to use a mixup of these solutions? Being a noob for me a transactionScope is already a lock, in a sense that during the transaction other machines cannot even access the same row in the Db but please help me to understand. Thanks

 public void Save(Document document){
using var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
               TransactionScopeAsyncFlowOption.Enabled);

          
            try
            {
                using (var lockHandler = documentLock.CreateLockForGuid(document.Guid))
                {
                    repositoryOne.Save(document);

                    repositoryTwo.Save(document);
                
                    scope.Complete();
               }
            }
}

lockhandler is just a wrapper which calls the distributedLock, SqlDistributedReaderWriterLock with the document.Guid as its name

0

There are 0 answers