I Use UnitOfWork Pattern with Entity Framework to expose DbContext using bellow code. So My question is that, is it poosible to get Context instance with Ninject ?

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;
        }
[...]

Now within NinjectWebCommon

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

Without using _dbContext ?? Activator.CreateInstance<C>(); , can it be possible to get DbContext instance via Ninject ?

有帮助吗?

解决方案

Yes it is possible . check the solution bellow

Ninject DI Configuration

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

And within 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;
            }

        }
[...]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top