2

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();
}
Hadi Sharifi
  • 1,497
  • 5
  • 18
  • 28
  • Using the InThreadScope inside an ASP.NET application is a very bad idea: http://stackoverflow.com/questions/14591422/why-is-perthreadlifetimemanager-used-in-this-example – Steven Mar 19 '14 at 12:18
  • You might also find this Q/A informative: http://stackoverflow.com/questions/10585478/one-dbcontext-per-web-request-why – Steven Mar 19 '14 at 12:19

1 Answers1

1

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

mipe34
  • 5,596
  • 3
  • 26
  • 38