Defined constructor object without parameters
I know this is a duplicate question, but I cannot find an answer to my error. I am trying to show a list of my rooms stored in the database, but I am getting the following error:
Server Error in '/' Application.
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a controller of type 'HotelProjectFinal.Controllers.RoomController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969412
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
But I have a constructor with a parameter:
namespace HotelProjectFinal.Controllers
{
public class RoomController : Controller
{
private IRoomRepository repository;
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
public ViewResult List()
{
return View(repository.Rooms);
}
}
}
My opinion:
@model IEnumerable<HotelProjectFinal.Models.Room>
@{
ViewBag.Title = "List";
}
@foreach (var p in Model)
{
<div class="item">
<h3>@p.Room_number</h3>
@p.Room_Type
<h4>@p.Room_Type.Price.ToString("c")</h4>
</div>
}
I am using ninject:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IRoomRepository>().To<EFRoomRepository>();
}
}
}
source to share
You have a factory controller, but the fact that the stacktrace says nothing about Ninject suggests that you forgot to tell MVC about it.
You can fix this by adding a line to say it.
However, it is recommended to use Ninject in adding a NuGet reference to Ninject.MVC3 . There are docs on this on the linked Ninject MVC3 wiki .
source to share
Try changing the 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 did not specify [Inject] above the constructor you want to use for dependency injection. This confused "Ninject" and threw an exception.
The main DI pattern is constructor injection. When activating an instance of type Ninject, select one of the constructor types to use by applying the following rules in the following order: -
- If the constructor has an [Inject] attribute, it is used (but if you apply the attribute to multiple, Ninject will throw a NotSupportedException at runtime upon detection).
- If none of the constructors has an [Inject] attribute, Ninject will choose the one with more parameters that Ninject knows how to resolve.
- If no constructors are defined, Ninject will choose the default parameterless constructor (assuming there is one).
More detailed information can be found here:
https://github.com/ninject/ninject/wiki/Injection-Patterns
As stated in Ruben, the [Inject] attribute pollutes the controller with external problems.
This links your code to a specific container. (Although Ninject allows you to customize a specific attribute for search, the point remains - you are polluting the interface with external issues.)
Your actual problem is probably related to a missing reference to Ninject.MVC3
Although IRoomRepository can be null, this does not make it a parameterless constructor. At first glance, it looks like your IoC is not properly connected to the IRoomRepository. Without 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;
}
Change, are you using Ninject.Mvc and your MvcHttpApplication base implements NinjectHttpApplication?
source to share