3

Entity Framework で UnitOfWork パターンを使用して、以下のコードを使用して 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>();
}

を使用せずに、 Ninjectを介してDbContextインスタンス_dbContext ?? Activator.CreateInstance<C>();を取得することはできますか?

4

1 に答える 1

3

はい、可能です。以下の解決策を確認してください

NinjectDI構成

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

        }
[...]
于 2013-01-14T20:03:51.167 に答える