如何使用Ninject将单个实例映射到各种类型?

时间:2011-10-17 18:54:44

标签: dependency-injection ninject

我有这个:

public class DbContext : System.Data.Entity.DbContext, IDbContext
{
}

我的Ninject配置:

public override void Load()
{
    Bind<IDbContext>().To<DbContext>().InRequestScope().WithConstructorArgument("connectionString", ConfigurationManager.AppSettings["DefaultConnectionString"]);
}

那么,我如何在另一个类中得到DbContext的相同实例,如:

public class ExampleClass()
{
   ...

   public ExampleClass(DbContext myDbContextDependency)
   {
      ...
   }
}

更新1:

IDbContext是我的 UnitOfWork模式,它存在于我的域层中:

public interface IDbContext
{
    void SaveChanges();
}

我需要在我的BaseRepository中使用DbContext

public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : Entity
{
   ...

   //I'm using DbContext here:
   protected BaseRepository()
   {
      this.DbSet = DbContext.Set(typeof(TEntity));
   }

   //and here:
   public virtual void Edit(TEntity entity)
   {
      this.DbContext.Entry(entity).State = EntityState.Modified;
   }
}

2 个答案:

答案 0 :(得分:1)

您应该注入IDbContext,而不是DbContext

public class ExampleClass()
{
   ...

   public ExampleClass(IDbContext myDbContextDependency)
   {
      ...
   }
}

答案 1 :(得分:0)

我使用Ninject的服务定位器找到了解决方案,并收回了DbContext的实例:

public class ExampleClass()
{
    protected DbContext DbContext
    {
        get
        {
                                                                        //Here I do the trick I wanted
            return DependencyResolverFactory.Instance.Get<IDbContext>() as DbContext;
        }
    }

    ...
}