Do not use "using" expression for TransactionScope

I always use the following format to use transactions.

using (TransactionScope scope = new TransactionScope ()) {
  ....
}

Sometimes I want to wrap a transaction in a new class, for example, the DbContext class, I want to use an instruction like

dbContext.Begin ();
...
dbContext.Submit ();

It seems that the transaction class needs to use the "using" statement to delete, I want to know if in any case not to use "use".

+3
source share
3 answers

You can create your class DbContextas follows:

public sealed class DbContext : IDisposable
{
    private bool disposed;
    private TransactionScope scope;

    public void Begin()
    {
        if (this.disposed) throw new ObjectDisposedException();
        this.scope = new TransactionScope();
    }

    void Submit()
    {
        if (this.disposed) throw new ObjectDisposedException();
        if (this.scope == null) throw new InvalidOperationException();
        this.scope.Complete();
    }

    public void Dispose()
    {
        if (this.scope != null)
        {
            this.scope.Dispose();
            this.scope = null;
        }
        this.disposed = true;
    }
}

and you can use it as follows:

using (var context = new DbContext())
{
    context.Begin();

    // Operations.

    context.Submit();
}
+10
source
using (var scope = new TransactionScope())
{
}

functionally equivalent to:

var scope = new TransactionScope();
try
{
}
finally
{
    scope?.Dispose();
}

(.. using , IDisposable.)

+15

try..finally Dispose , , .

+2

Source: https://habr.com/ru/post/1744475/


All Articles