Is there a way to create a nested using in a Disposable object, so this code:
using (var ctx = new MyEntities()) { ctx.Connection.Open(); using (var tx = dbContext.Connection.BeginTransaction()) { // ... do awesome things here ctx.SaveChanges(); tx.Commit(); } } to something like this:
using (var txContext = new TransactionContext()) { // ... do awesome things here } ?
Currently I have:
public class TransactionContext : IDisposable { private MyEntities DbContext { get; set; } private DbTransaction Transaction { get; set; } public TransactionContext() { DbContext = new MyEntities(); DbContext.Connection.Open(); Transaction = DbContext.Connection.BeginTransaction(); } void IDisposable.Dispose() { try { DbContext.SaveChanges(); Transaction.Commit(); } catch (Exception exception) { Transaction.Rollback(); DbContext.Dispose(); } } } I'm not sure if this is correct in ways of disposing the different Disposables, especially in case of an error/exception.
usingthenDisposewill be called and now you are callingSaveChangesandCommitwhen you probably shouldn't. Please read the MSDN article on the dispose patterncatch (Exception) {... throw;}Action. Then you just write the code that is different as a lambda and pass it to the method.