No parameterless constructor object defined

笑着哭i 提交于 2019-12-05 19:44:59

You've got a controller factory, but the fact that the stacktrace says nothing about Ninject suggests you have forgotten to tell MVC about it.

You could fix that by adding a line to tell it that.

However the recommended practice is to hook Ninject in by adding a NuGet reference to Ninject.MVC3. There are docs about it on the associated Ninject MVC3 wiki.

Please try changing your constructors to the following:

public RoomController() { } // You were missing this parameterless constructor

[Inject] 
public RoomController(IRoomRepository roomRepository) 
{
    repository = roomRepository;
}

Ninject is looking for a parameterless constructor because you haven't specified [Inject] above constructor that you wish to use for dependency injection. This has confused "Ninject" and caused an exception to be thrown.

The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-

  • If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).
  • If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
  • If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).

More information can be found here:

https://github.com/ninject/ninject/wiki/Injection-Patterns

As pointed out by Ruben, [Inject] attribute pollutes the controller with external concerns.

This ties your code to a specific container. (Although Ninject does permits the customization of the specific attribute to look for, the point remains – you’re polluting an interface with external concerns.)

Your actual problem probably relies in a missing reference to Ninject.MVC3

Even though IRoomRepository could be null, that doesn't make it a parameterless constructor. At first glace, it looks like your IoC isn't wired up correctly for IRoomRepository. With no IoC, or misconfigured IoC, the controller activator looks for a parameterless constructor for your controllers.

 // This is a parameterless constructor.
 public RoomController() 
 { }

 // This is not a parameterless constructor.
 public RoomController(IRoomRepository roomRepository) 
 {
     repository = roomRepository;
 }

Edit, Are you using Ninject.Mvc and your base MvcHttpApplication is implementing NinjectHttpApplication?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!