asp.net-mvc - ASP.NET MVC 2、Ninject 2.2 并且没有为此对象定义无参数构造函数

标签 asp.net-mvc asp.net-mvc-2 ninject ninject-2 ninject.web

所以我一直在使用 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 README 所说的):

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

还有一个看起来像这样的家庭 Controller :
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();
        }
    }
}

现在,每次我运行我的项目并访问“/”时,我都会看到一个黄色的死机屏幕,并显示一条消息“没有为此对象定义无参数构造函数”。似乎 Ninject 没有解决我的 Foo 服务并将其注入(inject) HomeController。我想我错过了一些非常明显的东西,但我只是没有看到它。

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

最佳答案

我:你能提供更多关于 IFoo 服务实现的信息吗?它是否满足了自己的所有依赖项?

我自己:嗯,不,它没有。原来我没有绑定(bind)它的依赖项。男孩,该错误消息和堆栈跟踪是否具有误导性!

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

关于asp.net-mvc - ASP.NET MVC 2、Ninject 2.2 并且没有为此对象定义无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765286/

相关文章:

javascript - jQuery 选择何时属性名称以?

c#-4.0 - MVC2 中 HttpNotFound 的替代方案

jquery - 如何确保我的 jQuery .ready 最终运行

asp.net-mvc-2 - ASP.NET : ActionLink return relative url

c# - 具体 .Net 类的依赖注入(inject)

c# - 如何将 Controller Action 的参数传递给 Ninject 具体类型?

c# - 最佳实践 : StructureMap and ASP. NET MVC 2 - 抽象基础 Controller 中的 Setter 注入(inject)/构造注入(inject)

asp.net-mvc - 如何在 ASP.NET MVC 应用程序中对 'Azure AD and OpenID Connect' 代码进行单元测试

asp.net-mvc - Web API 2 中具有 MVC 5 AttributeRouting 的 QueryString

c# - ninject 的循环依赖