No parameterless constructor defined for this object for MVC Controller - asp.net-mvc

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

Related

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

Autofac injecting to Controllers loaded with RegisterControllers()

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));

Structuremap does not work on MVC4

I've used StructureMap in MVC2/3 many times without any concern, but I guess handling IoC is different in MVC4.
When i used StructureMap for handling IoC in MVC4 I get the following exception.:
No parameterless constructor defined for this object
Why?
I have not found any correct result in google except this: IoC Not Working In MVC4
These is my IoC classes:
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
//scan.Assembly("DLL.Core");
scan.Assembly("DLL.CMS");
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
x.For<IDbContext>().Use<ModelEntities>();
x.For(typeof(IRepository<>)).Use(typeof(Repository<>));
x.For<IHttpControllerActivator>();
x.For<IController>();
});
return ObjectFactory.Container;
}
And SmDependencyResolver is:
public class SmDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public SmDependencyResolver(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType == null) return null;
try
{
return serviceType.IsAbstract || serviceType.IsInterface
? _container.TryGetInstance(serviceType)
: _container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
}
And my error is:
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
'Parsian.Web.Areas.Dashboard.Controllers.MemberController'. 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)
+196 System.Web.Mvc.<>c__DisplayClass6.b__2() +49 System.Web.Mvc.<>c__DisplayClassb1.<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(Func1 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()
+8862676 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Thanks for correct answers.
oops.I found an emergency solution :) Try to implement a class from IControllerActivator
public class StructureMapControllerActivator : IControllerActivator
{
private IContainer _container;
public StructureMapControllerActivator(IContainer container)
{
_container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
return _container.GetInstance(controllerType) as IController;
}
}
and then register it to the IoC class:
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
and then enjoy it.
Good luck
If you remove any old configuration for structuremap and install structurmap.mvc4 from nuget then configure your IoC container, you don't have any problems.
try adding this class as your ControllerFactory, I've actually seen the error above in MVC3 and this usually fixed it for me
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
return (controllerType == null)
? base.GetControllerInstance(requestContext, controllerType)
: ObjectFactory.GetInstance(controllerType) as IController;
}
catch (Exception ex)
{
return null;
}
}
}
Using StructureMap.MVC5.Update I had to do this or else the nested IContainer was already disposed (weird) :
public class StructureMapControllerActivator : IControllerActivator
{
public IController Create(RequestContext requestContext, Type controllerType)
{
return StructuremapMvc.StructureMapDependencyScope.GetInstance(controllerType) as IController;
}
}

how I can bind my datasource to view?

I have serious problem I can not pass my data to controller when the form submitted how I can solve this ?
//int controller class
[HttpPost]
public ActionResult Index(EnterpriseFramework.Entity.Synchronization.BindableEntity model)
{
//do something
}
and my view :
#model EnterpriseFramework.Entity.Synchronization.BindableEntity
<p>
#using (Html.BeginForm())
{
<fieldset>
<legend>title</legend>
<div>
#Html.HiddenFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Id)
</div>
<div>
#Html.LabelFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Number)
#Html.TextBoxFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Number)
</div>
<div>
#{
EnterpriseFramework.Entity.Synchronization.DataSource ds = Model.GetRelation("lnkLetterReceiver");
foreach (EnterpriseFramework.Entity.Synchronization.BindableEntity item in ds)
{
AutomationTest.Models.DTO.LetterReceiver childRece = item.Underlay.Entity as
AutomationTest.Models.DTO.LetterReceiver;
<div>
#Html.LabelFor(c=> childRece.oau_LetterReceiver_Name)
#Html.TextBoxFor(c=> childRece.oau_LetterReceiver_Name)
</div>
}
}
</div>
<div>
<input type="submit" name="Confirm" value="Confirm" />
</div>
</fieldset>
}
</p>
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.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +199
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +572
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8897857
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Every type that you are trying to use as action parameter must have a default parameterless constructor. Otherwise the default model binder will not be able to instantiate it and populate its properties.
That's why you should never use your domain models in views. You should define and use view models which are classes specifically design to meet the requirements of a given view. Then the controller action will map back and forth between the view models and the domain models. Like this:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// There were validation errors => redisplay the view
return View(model);
}
// the model is valid => map the view model to a domain model and process
...
}
That's as far as best practices are concerned. If your application has already been polluted and refactoring towards view models is not possible at the moment you have two possibilities:
Write a custom model binder for the BindableEntity type so that you manually invoke the proper constructor in the CreateModel method.
Add a default parameterless constructor to the BindableEntity type.
Use the TryUpdateModel method:
[HttpPost]
public ActionResult Index()
{
var model = new BindableEntity(WHATEVER);
if (!TryUpdateModel(model) || !ModelState.IsValid)
{
// There were validation errors => redisplay the view
return View(model);
}
// the model is valid => process
...
}
I assume you have only defined constructors with parameters? To fix this, you need to add this line of code
public BindableEntity()
{ }
To your EnterpriseFramework.Entity.Synchronization.BindableEntity class.
This will define a parameter-less constructor and will allow you to use it as you desire, although you do need to define a ViewModel in order to use MVC in the way it was designed.

Resources