如何通过Ninject在UnitOfWork中获取DbContext实例?

时间:2013-01-14 16:56:54

标签: entity-framework entity-framework-4 ninject unit-of-work ninject.web.mvc

我使用UnitOfWork Pattern with Entity Framework使用波纹管代码公开DbContext。所以我的问题是,使用Ninject获取Context实例是否合理?

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>();
}

不使用_dbContext ?? Activator.CreateInstance<C>();,是否可以通过 Ninject 获取 DbContext 实例?

1 个答案:

答案 0 :(得分: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;
            }

        }
[...]