我在mvc项目中实现工作单元模式,
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; }
}
}
还有存储库模式,
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; }
}
在Ninject中我使用InThreadScope作为工作单元,它是否正确?
private static void RegisterServices(IKernel kernel)
{
kernel.Bind(typeof(IUnitOfWork)).To(typeof(UnitOfWork)).InThreadScope();
}
答案 0 :(得分:1)
对于Web应用程序,请使用InRequestScope()
。不要忘记同时注册OnePerRequestModule
,因此UnitOfWork
/ db上下文将在请求结束时处理。
InRequestScope()
扩展程序目前位于Ninject.Web.Common