ASP.NET MVC 2,Ninject 2.2并没有为此对象定义的无参数构造函数

Jon*_*ney 5 asp.net-mvc ninject ninject.web ninject-2 asp.net-mvc-2

所以我花了一些时间与ASP.NET MVC 2(目前坚持使用Visual Studio 2008),现在已经开始使用Ninject 2.2及其MVC集成.我从以下位置下载了Ninject 2.2和Ninject.Web.Mvc:

https://github.com/downloads/ninject/ninject/Ninject-2.2.0.0-release-net-3.5.zip
https://github.com/downloads/ninject/ninject.web.mvc/Ninject.Web.Mvc2 -2.2.0.0-release-net-3.5.zip

并在我的MVC 2项目中引用它们.我的Global.asax.cs文件看起来像这样(几乎是Ninject.Web.Mvc自述文件所说的):

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject.Web.Mvc;
using Ninject;

namespace Mvc2 {
    public class MvcApplication : NinjectHttpApplication {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }

        protected override void OnApplicationStarted() {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }

        protected override IKernel CreateKernel() {
            var kernel = new StandardKernel();

            kernel.Bind<IFoo>().To<Foo>();

            return kernel;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和一个看起来像这样的家庭控制器:

using System;
using System.Web;
using System.Web.Mvc;

namespace Mvc2.Controllers {
    public class HomeController : Controller {
        private readonly IFoo foo;

        public HomeController(IFoo foo) {
            this.foo = foo;
        }

        public ActionResult Index() {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,每当我运行我的项目并访问'/'时,我会看到一个黄色的死亡屏幕,上面写着"没有为此对象定义无参数构造函数".似乎Ninject没有解析我的Foo服务并将其注入HomeController.我想我错过了一些非常明显的东西,但我只是没有看到它.

如何让Ninject将Foo注入HomeController,而不使用Ninject属性?

Jon*_*ney 4

:您能否提供有关 IFoo 服务实现的更多信息?它自己的所有依赖项是否都得到满足?

我自己:嗯,不,不是。事实证明我没有绑定它的依赖项。天哪,错误消息和堆栈跟踪是否具有误导性!


所以我的错误是我没有绑定 IFoo 实现的依赖项之一,因此 Ninject 无声地失败并尝试继续其快乐的方式。这真的很不幸,因为一旦我偏离了一个微不足道的设置,它可能会导致一些非常奇怪的行为。我想我的下一个问题应该是如何让 Ninject 尽早失败并提供有关问题所在的良好消息?但现在我至少可以继续下去。