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

2023-12-25

因此,我花了一些时间使用 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/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 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;
        }
    }
}

家庭控制器如下所示:

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 服务并将其注入 HomeController 中。我想我错过了一些非常明显的东西,但我只是没有看到它。

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


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

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


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC 2、Ninject 2.2 且没有为此对象定义无参数构造函数 的相关文章

随机推荐