开发者

not use "using" statement for TransactionScope

i always using the following format to use transactionscope.

using(TransactionScope sc开发者_如何转开发ope = new TransactionScope()){
  ....
}

sometimes i want to wrap the transactionscope to a new class, for example DbContext class, i want to using the statement like

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

it seems the transactioncope class need use "using"statement to do dispose, i want to know if there is anyway not use "using".


using (var scope = new TransactionScope())
{
    …
}

is functionally equivalent to:

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

(i.e. you can only use the using statement with types that implement the IDisposable interface.)


You can design your DbContext class as 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();
}


you can use a try..finally and call Dispose by yourself, but it's not as clear as the using form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜