【问题标题】:I'm using ninject 3.0 and asp.net mvc 3. I get the error rror activating IProductRepository我正在使用 ninject 3.0 和 asp.net mvc 3。我收到错误 rror 激活 IProductRepository
【发布时间】:2015-05-11 15:41:49
【问题描述】:

我是 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);
    }
}

【问题讨论】:

  • NinjectControllerFactory构造函数中调用AddBindings()
  • 这就是@MikeDebela 的问题。非常感谢您的快速答复!

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


【解决方案1】:

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

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

然后按照 Mike 的建议,从您的 NinjectControllerFactory 构造函数方法中调用它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多