Autofac injecting to Controllers loaded with RegisterControllers() - asp.net-mvc

Is there a way to enable injection in controllers loaded via builder.RegisterControllers() in an external assembly? When I copy the exact same assembly in my plugin folder, I get a parameterless constructor not found error.
// This doesnt work, parameterless constructor not found!
var assemblies = new DirectoryInfo(
HttpContext.Current.Server.MapPath("~/App_Plugins/"))
.GetFiles("*.dll")
.Select(r => Assembly.LoadFrom(r.FullName)).ToArray();
// This works, injection happens correctly on constructor
var assemblies = new[] {typeof (MvcApplication).Assembly};
The second one will work, while the first one will produce the error. I have tried manualy also registering the "external" controllers but still the same problem:
builder.RegisterAssemblyTypes(assemblies)
.Where(r => r.BaseType == typeof(Controller))
.InstancePerHttpRequest();
I am using the DefaultControllerFactory of mvc 4
Stack trace is this:
No parameterless constructor defined for this object.
[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, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'TestProject.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +191
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

I'm not seeing Autofac involved in the stack trace. If Autofac were unhappy the exception would look something like:
[DependencyResolutionException: None of the constructors found with 'Public binding flags' on type 'SomeApp.WebApplication.Areas.Shared.Controllers.AccountController' can be invoked with the available services and parameters:
Cannot resolve parameter 'SomeApp.WebApplication.Areas.Shared.Controllers.Slappy slappy' of constructor 'Void .ctor(SomeApp.Web.LoginService, SomeApp.Web.AccountMembership.IMembershipService, SomeApp.Infrastructure.Logging.ILog, SomeApp.WebApplication.Areas.Shared.Controllers.Slappy)'.]
Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +377
Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +48
Autofac.Core.Resolving.InstanceLookup.Execute() +48
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +167
Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +64
Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +163
Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) +70
Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) +53
Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType) +59
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41
[InvalidOperationException: An error occurred when trying to create a controller of type 'SomeApp.WebApplication.Areas.Shared.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +179
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) +196
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) +88
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() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Verify you are setting the DependencyResolver.
DependencyResolver.SetResolver(new AutofacDependencyResolver(ApplicationContainer));

Related

No parameterless constructor defined for this object for MVC Controller

I have this controller as you can see :
namespace Web.Front.Controllers
{
public class CarController : Controller
{
ICarService _CarService;
public CarController(ICarService carService)
{
_CarService = carService;
}
// GET: Car
public ActionResult Index()
{
return View();
}
}
}
When i call index action i get this error :
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, StackCrawlMark& stackMark) +119
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +11
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'Web.Front.Controllers.CarController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +102
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +184
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
As a note i am using ninject to inject services to controllers .when i remove the service from constructor it works .
The ninject code:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<DidbaanContext>().To<DidbaanContext>();
kernel.Bind<ICarService>().To<CarService>();
kernel.Bind<ICarRepository>().To<CarRepository>();
}
mvc needs parameterless contructions.
If you have no constructor, .Net-runtime create parameterless contruction automaticly, otherwise if you have a contruction with parameter, than the runtime don't do that and raise an error.
Ether you create a new carService on each controler, or you use a serviceProvider.
The unittest are simple with a serviceprovider.
With asp.net core its easy enter link description here, if you use mvc 4 or 5. you can see here a see here a sample enter link description here

Umbraco No parameterless constructor defined for this object

I am trying to render a partial view in Umbraco. I have a BaseLayout.cshtml,Homepage.cshtml,BaseLayoutViewModel,HomepageViewModel
This is my BaseLayout View
#inherits Umbraco.Web.Mvc.UmbracoViewPage<View_Models.BaseLayoutViewModel>
#{
Layout = null;
}
<!DOCTYPE html>
<html lang="en-gb">
<head>
</head>
<body>
#Html.Action("GetPrimaryNavbar", "PrimaryNavbar", Model) //This is there the site throws an error.
#RenderBody()
</body>
</html>
This is my BaseLayout Model. Homepage model inherits from base layout.
public class BaseLayoutViewModel : PublishedContentModel
{
public BaseLayoutViewModel(IPublishedContent content) : base(content)
{
}
public string PageTitle => this.GetPropertyValue<string>(FieldNames.BaseLayout.PageTitle);
public string PageDescription => this.GetPropertyValue<string>(FieldNames.BaseLayout.PageDescription);
public string NavigationName => this.GetPropertyValue<string>(FieldNames.BaseLayout.NavigationName);
}
My PrimaryNavbar Partial view is:
#inherits Umbraco.Web.Mvc.UmbracoViewPage<View_Models.PrimaryNavbarViewModel>
<header>
<ul>
<li>
</li
</ul>
</header>
And the controller for the PrimaryNavbar is:
public class PrimaryNavbarController : SurfaceController
{
[ChildActionOnly]
public ActionResult GetPrimaryNavbar(RenderModel model)
{
//var primaryNavbarViewModel = new PrimaryNavbarViewModel(model.Content);
return PartialView("PrimaryNavbar");//, primaryNavbarViewModel);
}
}
EDIT: Adding Full 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:
Line 28: <body>
Line 29:
Line 30: #Html.Action("GetPrimaryNavbar", "PrimaryNavbar", Model)
Line 31:
Line 32: #RenderBody()
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, StackCrawlMark& stackMark) +138
System.Activator.CreateInstance(Type type, Boolean nonPublic) +105
System.Activator.CreateInstance(Type type) +12
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +272
[MissingMethodException: No parameterless constructor defined for this object. Object type 'Umbraco.Web.Models.RenderModel'.]
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +346
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +744
Umbraco.Web.Mvc.RenderModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +122
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +460
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +137
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1167
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +170
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +455
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +42
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +170
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +881
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +170
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +699
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +94
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +170
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +539
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3614
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +131
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +36
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +595
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +114
ASP._Page_Views_BaseLayout_cshtml.Execute() in c:\Users\USERNAME\documents\visual studio 2015\projectsViews\BaseLayout.cshtml:30
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +253
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +148
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +122
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +311
System.Web.WebPages.WebPageBase.Write(HelperResult result) +108
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +89
System.Web.WebPages.WebPageBase.PopContext() +310
Umbraco.Core.Profiling.ProfilingView.Render(ViewContext viewContext, TextWriter writer) +232
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +375
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +90
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +186
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137
I cant understand why I am getting "No parameterless constructor defined for this object." Can someone help me on this?
Thanks
To solve the issue you need to send the model like this:
#Html.Action("GetPrimaryNavbar", "PrimaryNavbar", new { model = Model })

No parameterless constructor defined for the object

Just upgraded to from SC 8.0 to 8.1 Update3 and started see No parameterless constructor defined for the object error.
Any ideas what could be different between 8.0 and 8.1 rendering?
Solution includes Glass Mapper as well. I did not add any Areas since the 8.0 build was single site setup.
Full error:
[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, StackCrawlMark& stackMark) +138
System.Activator.CreateInstance(Type type, Boolean nonPublic) +105
System.Activator.CreateInstance(Type type) +12
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +73
[InvalidOperationException: An error occurred when trying to create a controller of type 'XOM.HR.Web.Controllers.Page.PageChromeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +240
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +103
Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext requestContext, String controllerName) +96
[ControllerCreationException: Could not create controller: 'PageChrome'.
The context item is: '/sitecore/content/Home'.
The current route url is: '{*pathInfo}'. This is the default Sitecore route which is set up in the 'InitializeRoutes' processor of the 'initialize' pipeline. ]
Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController(RequestContext requestContext, String controllerName) +202
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +267
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +95
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3614
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +131
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +36
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +595
System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName) +52
ASP._Page_Views_Shared_Layouts_Index_cshtml.Execute() in c:\inetpub\wwwroot\Website\Views\Shared\Layouts\Index.cshtml:5
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +253
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +148
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +122
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) +137
Sitecore.Mvc.Presentation.ViewRenderer.Render(TextWriter writer) +343
[InvalidOperationException: Error while rendering view: '~/Views/Shared/Layouts/Index.cshtml' (model: 'Sitecore.Mvc.Presentation.RenderingModel, Sitecore.Mvc').
]
Sitecore.Mvc.Presentation.ViewRenderer.Render(TextWriter writer) +826
Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer.Render(Renderer renderer, TextWriter writer, RenderRenderingArgs args) +30
Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer.Process(RenderRenderingArgs args) +75
(Object , Object[] ) +74

No parameterless constructor defined for this object in mvc4

using Michell.ClaimsAuditAdmin.Models;
using Mitchell.ClaimsAuditAdmin.Repositories;
using Mitchell.ClaimsAuditAdmin.Web.Models;
using System.Web.Mvc;
namespace Mitchell.ClaimsAuditAdmin.Web.Controllers
{
public class ClaimAuditAdminController : Controller
{
private readonly IClaimsAuditAdminRepository claimAuditAdminRepository;
public ClaimAuditAdminController(IClaimsAuditAdminRepository claimAuditAdminRepository)
{
this.claimAuditAdminRepository = claimAuditAdminRepository;
}
public ActionResult Index()
{
return View("SearchResultTest");
}
public ActionResult TestView()
{
return View("TestView");
}
public ViewResult DisplayClaimAuditView()
{
return View("_ClaimAuditAdminView");
}
public ActionResult SearchResultTest()
{
return View();
}
public ActionResult ClaimAuditReviewFilter()
{
//ClaimAuditModel objClaimAudit = new ClaimAuditModel();
//objClaimAudit.ClaimAudit_ID = 1;
//objClaimAudit.ClaimAudit_Name = "Claim1";
//objClaimAudit.FromDate = DateTime.Now.AddYears(-1);
//objClaimAudit.FromDate = DateTime.Now;
return PartialView("_ClaimAuditAdminView");
}
}
}
I know this question has been asked many times,but after reading all those SO similar questions i am not able to track my error.I have put the debugger in My controller's Constructor(ClaimAuditAdminController) but debugger doesn't goes there.
My Route.Config is
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ClaimAuditAdmin", action = "DisplayClaimAuditView", id = UrlParameter.Optional }
);
}
and the screen shot of my error is
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, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
+232 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a
controller of type
'Mitchell.ClaimsAuditAdmin.Web.Controllers.ClaimAuditAdminController'.
Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +179
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)
+197 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +49
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()
+301 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.17929
}
activator trying to create ur controller with parametrless constructor. but while your controller constructor has parameter
public ClaimAuditAdminController(IClaimsAuditAdminRepository claimAuditAdminRepository) <--this place
{
this.claimAuditAdminRepository = claimAuditAdminRepository;
}
the exception occurs.
Try to remove param from constructor or try override the DefaultControllerFactory
and create controller with parameter.
look here

Why am I getting a SecurityException on asp.net mvc when trying to bind to a collection

I'm using ASP.NET MVC 3.
It works fine on my machine, but I'm getting this error on the server.
Here is the Stack Trace:
[SecurityException: Request failed.]
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.RuntimeType.CreateInstanceImpl(BindingFlags
bindingAttr, Binder binder, Object[]
args, CultureInfo culture, Object[]
activationAttributes) +1136
System.Activator.CreateInstance(Type
type, BindingFlags bindingAttr, Binder
binder, Object[] args, CultureInfo
culture, Object[]
activationAttributes) +111
System.SecurityUtils.SecureCreateInstance(Type
type, Object[] args, Boolean
allowNonPublic) +93
System.ComponentModel.ReflectTypeDescriptionProvider.CreateInstance(Type
objectType, Type callingType) +92
System.ComponentModel.ReflectedTypeData.GetConverter(Object
instance) +346
System.ComponentModel.DefaultTypeDescriptor.System.ComponentModel.ICustomTypeDescriptor.GetConverter()
+63 System.ComponentModel.DefaultTypeDescriptor.System.ComponentModel.ICustomTypeDescriptor.GetConverter()
+97 System.ComponentModel.TypeDescriptor.GetConverter(Type
type) +23
System.Web.Mvc.ModelMetadata.get_IsComplexType()
+13 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +357
System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext
controllerContext, ModelBindingContext
bindingContext, PropertyDescriptor
propertyDescriptor, IModelBinder
propertyBinder) +17
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext
controllerContext, ModelBindingContext
bindingContext, PropertyDescriptor
propertyDescriptor) +367
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +94
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext, Object model) +55
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +1228
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
controllerContext, ModelBindingContext
bindingContext) +385
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext
controllerContext, ParameterDescriptor
parameterDescriptor) +303
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext
controllerContext, ActionDescriptor
actionDescriptor) +105
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
+329 System.Web.Mvc.Controller.ExecuteCore()
+115 System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +94
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +10
System.Web.Mvc.<>c_DisplayClassb.b_5()
+37 System.Web.Mvc.Async.<>c_DisplayClass1.b_0()
+21 System.Web.Mvc.Async.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult
_) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End()
+55 System.Web.Mvc.<>c_DisplayClasse.b_d()
+31 System.Web.Mvc.SecurityUtil.b_0(Action
f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action
action) +23
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +59
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+184
Here is the method signature:
[HttpPost]
public ActionResult Editar(Pessoa model, Movimentacao[] movimentacoes, FormCollection form){...}
Here is the data that I'm posting to the server:
IdPessoa=63&input-tab=7&Nome=Andrea+S.+Gomes&CPF=&Identidade=&DataNascimento=&Sexo=f&EstadoCivil.IdEstadoCivil=2&Profissao.IdProfissao=-1&ProfissaoDescricao=&DataConversao=&BatismoData=&BatismoIgreja=&BatismoPastor=&Endereco=&Complemento=&Estado.IdEstado=1&Cidade.IdCidade=1&Bairro.IdBairro=7&CEP=&Referencia=&Telefone1=&Telefone2=&Email=&Messenger=&Twitter=&PessoaVinculo.IdPessoaVinculo=2&Congregacao.IdCongregacao=6&Ativo=true&Ativo=false&Discipulador.IdPessoa-input=&Discipulador.IdPessoa=&UltimaVisita=&Conectado=false&PequenoGrupo.IdPequenoGrupo=-1&Observacao=&Competencia3=false&Competencia1=false&Competencia2=false&movimentacoes%5B0%5D.IdMovimentacao=0&movimentacoes%5B0%5D.Data=&movimentacoes%5B0%5D.MovimentacaoTipo.IdMovimentacaoTipo=-1&submitButton=
It might not work because on the server you are trying to run this site the security level could be set to low which would restrict reflection code to run. Such things might happen on shared hosts.

Resources