C# ASP.NET MVC 4 + Ninject MVC 3 = 没有为此对象定义无参数构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12311479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 4 + Ninject MVC 3 = No parameterless constructor defined for this object
提问by Gup3rSuR4c
UPDATE - Please look at my answer for a link and explanation of the solution to this problem
更新 - 请查看我的回答以获取此问题解决方案的链接和说明
Before we start, I know this is a very common question and I've been using Ninject for many moons without issues, but now it's come up and I can't figure out a fix. Also, no, none of the results on Google and SO so far have helped me.
在我们开始之前,我知道这是一个非常常见的问题,我已经在许多卫星上使用 Ninject 没有问题,但现在出现了,我想不出解决办法。另外,不,到目前为止,Google 和 SO 上的所有结果都没有帮助我。
So, consider the following bit of code running on a very, very, very simple prototype ASP.NET MVC 4 project from Visual Studio 2012 on Windows Server 2008 R2:
因此,请考虑在 Windows Server 2008 R2 上的 Visual Studio 2012 的一个非常、非常、非常简单的原型 ASP.NET MVC 4 项目上运行的以下代码:
public class DefaultController : Controller {
private IGroupPrincipalRepository GroupPrincipalRepository { get; set; }
[Inject]
public DefaultController(
IGroupPrincipalRepository groupPrincipalRepository) {
this.GroupPrincipalRepository = groupPrincipalRepository;
}
}
And here's the NinjectWebCommon.cs RegisterServicesmethod:
这是NinjectWebCommon.cs RegisterServices方法:
kernel.Bind(typeof(IGroupPrincipalRepository)).ToConstructor(
c =>
new GroupPrincipalRepository(new PrincipalContext(ContextType.Domain, "?", "?", "?", "?"))).InSingletonScope();
Now, this is how my other projects that use Ninject (but are ASP.NET MVC 3 on .NET 4) work and as far as I know this is what's needed to make everything work. So, why am I suddenly getting No parameterless constructor defined for this object.exceptions?
现在,这就是我使用 Ninject(但在 .NET 4 上是 ASP.NET MVC 3)的其他项目的工作方式,据我所知,这是使一切正常工作所需要的。那么,为什么我突然得到没有为此对象定义的无参数构造函数。例外?
UPDATE
更新
Here's the full NinjectWebCommon.csfile:
这是完整的NinjectWebCommon.cs文件:
[assembly: WebActivator.PreApplicationStartMethod(typeof(App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(App_Start.NinjectWebCommon), "Stop")]
namespace App_Start {
using System;
using System.DirectoryServices.AccountManagement;
using System.Repositories.ActiveDirectory;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon {
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start() {
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop() {
bootstrapper.ShutDown();
}
private static IKernel CreateKernel() {
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(
IKernel kernel) {
kernel.Bind(typeof(IGroupPrincipalRepository)).ToConstructor(
c =>
new GroupPrincipalRepository(new PrincipalContext(ContextType.Domain, "", "", "", ""))).InSingletonScope();
}
}
}
UPDATE - Please look at my answer for a link and explanation of the solution to this problem
更新 - 请查看我的回答以获取此问题解决方案的链接和说明
采纳答案by Gup3rSuR4c
Well, I don't have an exact answer whythe error is coming up, but I do know whois causing it and that is Visual Studio 2012. I installed Visual Studio 2010 on the same machine as 2012, installed ASP.NET MVC 4 for 2010 and I recreated the 2012 project into 2010 word for word, letter for letter. The final result is that when 2010 debugs the project everything works fine and Ninject injects the dependencies as it should.
好吧,我没有确切的答案为什么会出现错误,但我知道是谁导致的,那就是 Visual Studio 2012。我在 2012 年的同一台机器上安装了 Visual Studio 2010,安装了 ASP.NET MVC 4对于 2010 年,我将 2012 年的项目重新创建为 2010 年的逐字逐字逐字逐句。最终的结果是,当 2010 年调试项目时,一切正常,Ninject 按其应有的方式注入依赖项。
When 2012 debugs its project it just comes up with the No parameterless constructor defined for this objectexception. Re-targeting between .NET 4.0 and .NET 4.5 in 2012 doesn't do anything. Re-installing Ninject from NuGet also doesn't do anything. I even configured both 2010 and 2012 projects to use the local IIS server to be absolutely sure and the end result is the same.
当 2012 年调试它的项目时,它只是出现了No parameterless constructor defined for this object异常。2012 年在 .NET 4.0 和 .NET 4.5 之间重新定位没有任何作用。从 NuGet 重新安装 Ninject 也没有任何作用。我什至将 2010 和 2012 项目都配置为使用本地 IIS 服务器以绝对确定并且最终结果是相同的。
I'm going to assume that there's a bug with Visual Studio 2012 or with Ninject. The only difference I've got between the two projects is which IDE they're running from and the 2012 project is the one that's crashing so that's why I'm pointing the finger at Visual Studio 2012.
我将假设 Visual Studio 2012 或 Ninject 存在错误。我在这两个项目之间的唯一区别是它们运行的是哪个 IDE,而 2012 项目是崩溃的项目,所以这就是我将矛头指向 Visual Studio 2012 的原因。
UPDATE
更新
Guys. GUYS! I ran into this problem AGAIN, and found the solution in another SO question: Ninject + MVC3 is not injecting into controller.
伙计们。伙计们!我再次遇到这个问题,并在另一个 SO 问题中找到了解决方案:Ninject + MVC3 is not injection into controller。
Basically, this is what's missing from the Web.config which makes it work:
基本上,这是 Web.config 所缺少的,这使它起作用:
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
I'm guessing this forces the framework to be aware of IoC containers which allows Ninject the finally be able to bind. Although, I can't help but think that the Ninject NuGet package should look for the existence of that binding redirect in the Web.config and auto-magically add it. It sure would help with a lot of hair pulling happening over this issue.
我猜这会迫使框架意识到 IoC 容器,这使得 Ninject 最终能够绑定。虽然,我不禁认为 Ninject NuGet 包应该在 Web.config 中查找该绑定重定向的存在并自动神奇地添加它。它肯定会帮助解决这个问题上发生的大量头发问题。
P.S. Up-vote the snot out of that post I linked because it deserves it!
PS 为我链接的那篇文章中的鼻涕点投票,因为它值得!
回答by Kim Th?rning
I got the same error message after getting the MVC3 from NuGet.
I don't know if you got your project setup the same way as I do but my web.configis auto generated depending on environment. The MVC from NuGet is adding rows (<runtime>)to the web.configand those rows were removed since my merging config-files wasn't setup correctly.
从 NuGet 获取 MVC3 后,我收到了相同的错误消息。
我不知道你的项目设置是否和我一样,但我的项目web.config是根据环境自动生成的。来自 NuGet 的 MVC 正在添加rows (<runtime>)到web.config并且这些行已被删除,因为我的合并配置文件设置不正确。
Regards,
问候,
Kim
金
回答by Jere.Jones
I know this is an old question but there don't seem to be any real answers and I've worked around the problem so here is my solution:
我知道这是一个老问题,但似乎没有任何真正的答案,我已经解决了这个问题,所以这是我的解决方案:
Create a custom controller factory:
创建自定义控制器工厂:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory(IKernel kernel)
{
ninjectKernel = kernel;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (controllerType == null) ? null : (IController) ninjectKernel.Get(controllerType);
}
}
Then, if you are using NinjectHttpApplication, add the following line to OnApplicationStarted:
然后,如果您使用的是 NinjectHttpApplication,请将以下行添加到 OnApplicationStarted:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(Kernel));
If you aren't using NinjectHttpApplication, then add that line somewhere after you have created your kernel and pass it a reference to your freshly created kernel.
如果您没有使用 NinjectHttpApplication,请在创建内核后在某处添加该行,并将其传递给新创建的内核的引用。
That's it.
就是这样。
回答by JasonCoder
I was pulling my hair out on this for several hours on a recent project that I moved from MVC 3 to MVC 4. With the lack of on point answers I figured it had to be something I did as it appears that the Ninject.MVC3 nuget package will work fine with MVC 4 - and indeed it does.
在我从 MVC 3 转移到 MVC 4 的最近一个项目中,我为此纠结了几个小时。由于缺乏重点答案,我认为这必须是我所做的事情,因为看起来 Ninject.MVC3 nuget包将在 MVC 4 中正常工作 - 确实如此。
In my case I wasn't fully upgrading the MVC3 project. After following this guideI got things to work as expected. My guess was that I was missing an assembly binding redirect.
就我而言,我没有完全升级 MVC3 项目。遵循本指南后,我让事情按预期工作。我的猜测是我缺少程序集绑定重定向。
So if you're upgrading an MVC 3 project to MVC 4, using Ninject and getting the no parameterless constructor defined error, hope this helps.
因此,如果您将 MVC 3 项目升级到 MVC 4,使用 Ninject 并获得无参数构造函数定义的错误,希望这会有所帮助。
回答by juhan_h
As all of the previous posters have stated this caused me some gray hairs. In my case I had "optimised" my references too much. Ninject.* stuff was there but had gotten mangled up. I deleted all the references and cleaned packages.conf manualli and added the packages again - victory!
正如之前所有的海报所说,这让我头发花白。就我而言,我“优化”了我的参考文献太多。Ninject.* 东西在那里,但已经被破坏了。我删除了所有引用并清理了 packages.conf 手册并再次添加了这些包 - 胜利!
回答by wallice
Here is a dirty solution! Put this
这是一个肮脏的解决方案!把这个
var type = typeof(Ninject.Web.Mvc.MvcModule);
in the beginning of the AppStart event (or anywhere else )
在 AppStart 事件的开头(或其他任何地方)
Now let me explain what it means if someone didn't get trick yet. Thing is our http application class could reside anywhere in solution. Not only in web application. And this is very important because asp.net compilation routine is different from usual library applications. It eagerly loads ALL referenced libraries via BuildManager helper, while usually clr doesn't load types from start unless they're directly used.
现在让我解释一下如果有人还没有被骗是什么意思。事情是我们的 http 应用程序类可以驻留在解决方案中的任何地方。不仅在 Web 应用程序中。这一点非常重要,因为asp.net 编译例程与通常的库应用程序不同。它通过 BuildManager 帮助程序急切地加载所有引用的库,而通常 clr 不会从一开始就加载类型,除非它们被直接使用。
Now let's get back to our situation: Ninject.Web.Mvc work as dynamic plugin, which doesn't require any mention within a code. And thus is not loaded if it was referenced inside Class library which leads to broken Mvc.Dependancy initialization.
现在让我们回到我们的情况:Ninject.Web.Mvc 作为动态插件工作,不需要在代码中提及任何内容。因此,如果在类库中引用它会导致 Mvc.Dependancy 初始化中断,则不会加载它。
回答by MovGP0
The Problem seems to occur when one uses Visual Studio 2012/2013 with ASP.NET 4.0/4.5. The version of System.Web.Mvcwas set to 4.0.0.0in the Web.configfile. It did not work.
当使用带有 ASP.NET 4.0/4.5 的 Visual Studio 2012/2013 时,似乎会出现此问题。的版本在文件中System.Web.Mvc设置为。这没用。4.0.0.0Web.config
My solution was to
我的解决方案是
- delete
NinjectWebCommon.cs copy Dere Jone's
NinjectControllerFactoryclass into the project:public class NinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory(IKernel kernel) { ninjectKernel = kernel; } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return (controllerType == null) ? null : (IController) ninjectKernel.Get(controllerType); } }change the content of
Global.asaxto:public class MvcApplication : NinjectHttpApplication { protected override IKernel CreateKernel() { IKernel kernel = new StandardKernel(); // kernel.Load(Assembly.GetExecutingAssembly()); // kernel.Bind<ISomeClass>().To<SomeClass>(); return kernel; } protected override void OnApplicationStarted() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(Kernel)); } }after that your injections should work.
- 删除
NinjectWebCommon.cs 将 Dere Jone 的
NinjectControllerFactory类复制到项目中:public class NinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory(IKernel kernel) { ninjectKernel = kernel; } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return (controllerType == null) ? null : (IController) ninjectKernel.Get(controllerType); } }将内容
Global.asax改为:public class MvcApplication : NinjectHttpApplication { protected override IKernel CreateKernel() { IKernel kernel = new StandardKernel(); // kernel.Load(Assembly.GetExecutingAssembly()); // kernel.Bind<ISomeClass>().To<SomeClass>(); return kernel; } protected override void OnApplicationStarted() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(Kernel)); } }之后你的注射应该有效。
回答by Samuel
I have the same problem and the only thing that works for me is to change the "Local IIS Web server" in the Web project properties to "Use Visual Studio Development Server".
我有同样的问题,唯一对我有用的是将 Web 项目属性中的“本地 IIS Web 服务器”更改为“使用 Visual Studio 开发服务器”。


I don't know why but when I do this, my break point in NinjectWebCommon is hited. Like @Alex said, it's something with Visual Studio 2012 not enough bright to execute the code in NinjectWebCommon each time you build your application. It's also possible that it's me not enough bright to understand how it works under the hood.
我不知道为什么,但是当我这样做时,我在 NinjectWebCommon 中的断点被击中了。就像@Alex 所说的那样,每次构建应用程序时,Visual Studio 2012 不够亮,无法在 NinjectWebCommon 中执行代码。也有可能是我不够聪明,无法理解它是如何工作的。
I don't like my solution because I would prefer to use my Local IIS Web Server but for the moment, I have an application to create and to much time took with this $%?!!/ bug..feature..not sure.
我不喜欢我的解决方案,因为我更喜欢使用我的本地 IIS Web 服务器,但目前,我有一个应用程序要创建,并且用这个 $% 花费了很多时间?!/错误..功能..不确定.
回答by hanzolo
This was solved for me by adding a reference via Nuget to Ninject.Web.MVC.
通过 Nuget 添加对 Ninject.Web.MVC 的引用为我解决了这个问题。
回答by dawidg
I tried all these solutions, but none worked.
我尝试了所有这些解决方案,但没有一个奏效。
This is how I resolved it: Deleted all my temp asp.net files. After I'd done this, I got new config errors. I fixed them. The last, and real error came out: new Bootstrapper() was trying to load an older version of a ninject dll. Removed all ninject packages. Installed ninject nuget packages one by one, make triply sure that the correct version is installed.
我是这样解决的:删除了我所有的临时 asp.net 文件。完成此操作后,我收到了新的配置错误。我修好了。最后一个也是真正的错误出现了:new Bootstrapper() 试图加载旧版本的 ninject dll。删除了所有 ninject 包。一一安装ninject nuget包,三重确保安装了正确的版本。

