Reputation: 1527
I implement unit of work pattern in mvc project,
public class UnitOfWork : IUnitOfWork
{
private TransactionScope _transaction;
private readonly BodoShopEntities _db;
public UnitOfWork()
{
_db = new BodoShopEntities();
}
public void Dispose()
{
if (_db != null)
{
_db.Dispose();
}
System.GC.SuppressFinalize(this);
}
public void StartTransaction()
{
_transaction = new TransactionScope();
}
public void Commit()
{
_db.SaveChanges();
_transaction.Complete();
}
public DbContext Db
{
get { return _db; }
}
}
Also repository pattern,
public partial interface IRepository<T> where T : class
{
T GetById(object id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
IQueryable<T> Table { get; }
T Single(object primaryKey);
T SingleOrDefault(object primaryKey);
bool Exists(object primaryKey);
IUnitOfWork UnitOfWork { get; }
}
In Ninject I use InThreadScope for unit of work, Is it correct?
private static void RegisterServices(IKernel kernel)
{
kernel.Bind(typeof(IUnitOfWork)).To(typeof(UnitOfWork)).InThreadScope();
}
Upvotes: 2
Views: 231
Reputation: 5666
For web application use InRequestScope()
. Do not forget to register OnePerRequestModule
as well, so the UnitOfWork
/db context will be disposed at the end of the request.
InRequestScope()
extension is currently located at Ninject.Web.Common
Upvotes: 1