【问题标题】:How mapping various types with a single instance using Ninject?如何使用 Ninject 将各种类型映射到单个实例?
【发布时间】:2011-10-17 18:54:44
【问题描述】:

我有这个:

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

而且我需要 DbContext 在我的 BaseRepository 中使用:

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

【问题讨论】:

  • 我很好奇。如果你在整个请求中重复使用相同的上下文,你在哪里调用SaveChanges
  • 您可能应该将您创建的DbContext 类更改为不同的名称,以避免命名冲突。我看到您正在使用 EF 的 DbContext 的完整命名空间名称,但为了将来的维护者,请使用不同的类名。
  • @Omar 谢谢奥马尔,我会考虑的。

标签: dependency-injection ninject


【解决方案1】:

你应该注入一个IDbContext,而不是DbContext

public class ExampleClass()
{
   ...

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

【讨论】:

    【解决方案2】:

    我使用Ninject的Service Locator找到了解决方案,并取回了DbContext的实例:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多