我正在使用ninject 3.0和asp.net mvc 3.我得到错误激活IProductRepository

时间:2015-05-11 15:41:49

标签: c# asp.net asp.net-mvc asp.net-mvc-3 ninject

我是MVC的新手,所以即便放弃一本书的例子。但是当我运行程序时它会给我错误:激活IProductRepository时出错 没有匹配的绑定可用,并且该类型不可自绑定。 激活路径...

我已经阅读过一堆文章和其他错误,但是这些都没有帮助。 如果一切都与图书示例中的相同,为什么会发生这种情况?请一些帮助真的很感激。

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
    }

    protected override IController GetControllerInstance(RequestContext requestContext,
       Type controllerType)
    {
        return controllerType == null
            ? null
            : (IController)ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>(); 
    }
}

的Global.asax.cs

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
    }

IProductRepository.cs

public interface IProductRepository
{
    IQueryable<Product> Products { get; }
}

EFProductRepository.cs

public class EFProductRepository : IProductRepository
{
   private EFDbContext context = new EFDbContext();
   public IQueryable<Product> Products
    {
        get { return context.Products; }           
    }
}

public class EFDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }    
}

ProductController.cs

public class ProductController : Controller
{
    private IProductRepository repository;

    public ProductController(IProductRepository repoParam)
    {
        repository = repoParam;
    }

    public ViewResult List()
    {
        return View(repository.Products);
    }
}

1 个答案:

答案 0 :(得分:1)

更改您的方法以接受IKernel参数:

private void AddBindings(IKernel kernel)
{
    kernel.Bind<IProductRepository>().To<EFProductRepository>(); 
}

然后,迈克建议从你的NinjectControllerFactory构造函数方法中调用它:

public NinjectControllerFactory()
{
    ninjectKernel = new StandardKernel();
    AddBindings(ninjectKernal);
}