Entity framework MVC3和x2B;Ninject+;实体框架4

Entity framework MVC3和x2B;Ninject+;实体框架4,entity-framework,entity-framework-4,asp.net-mvc-3,ninject,Entity Framework,Entity Framework 4,Asp.net Mvc 3,Ninject,我有这个依赖解析程序 public class NinjectDependencyResolvercs : IDependencyResolver { private readonly IResolutionRoot resolutionRoot; public NinjectDependencyResolvercs(IResolutionRoot kernel) { resolutionRoot = kernel;

我有这个依赖解析程序

public class NinjectDependencyResolvercs : IDependencyResolver
    {
        private readonly IResolutionRoot resolutionRoot;
        public NinjectDependencyResolvercs(IResolutionRoot kernel)
        {
            resolutionRoot = kernel;
        }

        public object GetService(Type serviceType)
        {
            return resolutionRoot.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return resolutionRoot.GetAll(serviceType);
        }
    }
所有其他属性都会警告此错误:

'System.Data.Entity.DbContext' does not contain a definition for 'JobAdverts' and no extension method 'JobAdverts' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?)   

有人知道为什么DI不适用于类DbContext吗?

如果我理解正确,您注入的DbContext没有这些方法/属性,正如它们在派生类型SqlDataContext中声明的那样。 您需要注入SqlDataContext。如果要使用接口,则需要从SqlDataContext提取接口

编辑:

Ninject在运行时绑定,而您得到的错误(我猜想)是在编译时。你可以通过使用动态关键词来解决这个问题,但这只是解决问题

public class SqlRepository
{
    private dynamic dataContext;
    public SqlRepository(DbContext dataContext) {
        this.dataContext = dataContext;
    }
    ...
}
您需要做的是更改签名以使用SqlDataContext:

public class SqlRepository
{
 private SqlDataContextdata Context;
    public SqlRepository(SqlDataContextdata Context) {
        this.dataContext = dataContext;
    }
  ...
}
因为DbContext不包含这些方法,所以只有SqlContext包含这些方法。并且您的sqlcontext在运行时绑定到DbContext

dataContext.Users
'System.Data.Entity.DbContext' does not contain a definition for 'JobAdverts' and no extension method 'JobAdverts' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?)   
public class SqlRepository
{
    private dynamic dataContext;
    public SqlRepository(DbContext dataContext) {
        this.dataContext = dataContext;
    }
    ...
}
public class SqlRepository
{
 private SqlDataContextdata Context;
    public SqlRepository(SqlDataContextdata Context) {
        this.dataContext = dataContext;
    }
  ...
}