我总是使用以下格式来使用transactionscope.
using(TransactionScope scope = new TransactionScope()){ .... }
有时我想将Transactionscope包装到一个新类,例如DbContext类,我想使用像这样的语句
dbContext.Begin(); ... dbContext.Submit();
似乎事务管理器类需要使用“using”语句来进行处理,我想知道是否还有使用“使用”.
解决方法
您可以按如下方式设计DbContext类:
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; } }
你可以按如下方式使用它:
using (var context = new DbContext()) { context.Begin(); // Operations. context.Submit(); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。