3

我使用UnitOfWork Pattern與Entity Framework來使用下面的代碼公開DbContext。所以我的問題是,用Ninject獲取Context實例是否可行?如何通過Ninject在UnitOfWork中獲取DbContext實例?

IUnitOfWork

public interface IUnitOfWork<C> : IDisposable 
{ 
     int Commit(); 
     C GetContext { get; set; } 
} 

的UnitOfWork

public class UnitOfWork<C> : IUnitOfWork<C> where C : DbContext 
    { 
     private bool _disposed; 
     private readonly C _dbContext = null; 

     public UnitOfWork() 
     { 
      GetContext = _dbContext ?? Activator.CreateInstance<C>(); 
     } 

     public int Commit() 
     { 
      return GetContext.SaveChanges(); 
     } 


     public C GetContext 
     { 
      get; 
      set; 
     } 
[...] 

現在內NinjectWebCommon

private static void RegisterServices(IKernel kernel) 
{ 
    kernel.Bind<IUnitOfWork<MyDbContext>>().To<UnitOfWork<MyDbContext>>().InRequestScope(); 
    kernel.Bind<IEmployeeRepository>().To<EmployeeRepository>(); 
} 

w ^沒有使用_dbContext ?? Activator.CreateInstance<C>();,是否可以通過Ninject獲得DbContext實例?

+0

內你試過構造函數注入? – jrummell

+0

'kernel.Bind ().ToSelf().InRequestScope();'我可以做到嗎?但是UnitOfWork中的代碼是什麼? –

+0

我不熟悉Ninject,但我會假設你可以添加一個接受'C'參數的構造函數:'public UnitOfWork(C context)'。 – jrummell

回答

3

是的,這是可能的。檢查波紋管

Ninject DI配置

kernel.Bind<MyDbContext>().ToSelf().InRequestScope(); 
kernel.Bind<IUnitOfWork<MyDbContext>>().To<UnitOfWork<MyDbContext>>(); 
kernel.Bind<IEmployeeRepository>().To<EmployeeRepository>(); 

與解決的UnitOfWork

public class UnitOfWork<C> : IUnitOfWork<C> where C : DbContext 
    { 
     private readonly C _dbcontext; 

     public UnitOfWork(C dbcontext) 
     { 
      _dbcontext = dbcontext; 
     } 

     public int Commit() 
     { 
      return _dbcontext.SaveChanges(); 
     } 

     public C GetContext 
     { 
      get 
      { 
       return _dbcontext; 
      } 

     } 
[...]