I have a repository like so:
public interface IRepository
{
void Save<T>(T entity);
void Create<T>(T entity);
void Update<T>(T entity);
void Delete<T>(T entity);
IQueryable<T> GetAll<T>();
}
My question is, where should my transaction boundaries be? Should I open a new transaction on every method and commit it before returning? Or should it be around the entire repository so that the transaction is only committed when the repository is disposed/garbage collected?
Unit of Work is definitely the way to go. If you’re using SQL Server with a local database,
TransactionScopewill do most of the heavy lifting for you; as long as you share sessions between repositories (which you’re doing through constructor injection, right…?), then you can nest these to your heart’s content. By default, it enlists in the “ambient” transaction if there is one, and starts a new one if there isn’t, which is exactly the behaviour you want for a unit of work.So your repositories might look like this:
Then you can perform the complete unit of work like so:
If you don’t like
TransactionScopeor your environment prevents you from using it effectively then you can always implement your own UOW or use an existing implementation. Or if you’re just an architectural neat-freak then you can do both – use a generic unit-of-work interface with one of the main DI libraries, and implement your concrete UOW using theTransactionScope.