MVC: No parameterless constructor defined for this object

I have the following controller definition

public class FeaturedAccommodationController : Controller
{
   ...

   public FeaturedAccommodationController(IAccommodationService accommodationService)
   {
      ...
   }

   public ActionResult Index(int page = 1)
   {
      ...
   }
   ...
}

I have a link that I use to call this index action method

@Html.ActionLink("Featured Accommodations", "Index", "FeaturedAccommodation")

For some reason when I click on this link I get the following error. What is the problem here?

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 'JattCore.UI.Admin.Controllers.FeaturedAccommodationController'. 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() +8970356
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Answers


When you create your controller it needs in the constructor a parameter, called IAccommodationService. If you don't, you can't create the controller.

One way to solve the problem is to use Dependency Injection (DI)/ Inversion of Control (IoC) like ninject or similar. If you have one, then remember to register the IAccommodationService...


Add a constructor with no parameters to your Controller

public class FeaturedAccommodationController : Controller
{
   public FeaturedAccommodationController ()
   {
   }
   // your other parameterized constructors and action methods here
}

The problem is exactly what the error message states, there is no default parameterless constructor (e.g):

public FeaturedAccommodationController()
{
}

The MVC runtime can't instantiate your controller as it can't provide an implementation of IAccommodationService. You either need to do poor man's constructor injection like this:

public FeaturedAccommodationController()
    : this(new AccommodationService())
{
}

public FeaturedAccommodationController(IAccommodationService accommodationService)
{
}

or use an IOC container (such as Unity, Ninject, Windsor etc) which can build your controllers and resolve their dependencies.


Your question is almost an exact duplicate of this question:

Windows Azure, MVC3, No parameterless constructor defined for this object

Your error trace even points to the issue:

[InvalidOperationException: An error occurred when trying to create a controller of type 'JattCore.UI.Admin.Controllers.FeaturedAccommodationController'. Make sure that the controller has a parameterless public constructor.]


  • Stop IIS
  • Delete C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root
  • Start IIS

You can used a built-in feature of ASP.NET MVC by implementing DefaultControllerFactory and set it with ControllerBuilder.Current.SetControllerFactory


One reason this could happen is because this is your first and only controller in your application . My suggestion is having a default controller called Home with no constructor (as the error states) and then add another controller - the one you mentioned, that can have a constructor.


Need Your Help

C# How to find if an event is hooked up

c# hook event-handling

I want to be able to find out if an event is hooked up or not. I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event. I don't

Android: How to sum all the columns in a SQLite database and return 1 single variable

java android database sqlite sum

My objective is to sum all the columns in my database and return a variable 'total' = x amount.