Для этого объекта не определен беспараметрический конструктор для MVC Controller - PullRequest
0 голосов
/ 14 июня 2019

У меня есть этот контроллер, как вы можете видеть:

namespace Web.Front.Controllers
{
    public class CarController : Controller
    {
        ICarService _CarService;
        public  CarController(ICarService carService)
        {
            _CarService = carService;
        }

        // GET: Car

        public ActionResult Index()
        {

            return View();
        }
    }
}

Когда я вызываю действие index, я получаю эту ошибку:

 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

Как примечание, я использую ninject для внедрения сервисов в контроллеры. Когда я удаляю сервис из конструктора, он работает.

Код объекта:

  private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<DidbaanContext>().To<DidbaanContext>();
        kernel.Bind<ICarService>().To<CarService>();
        kernel.Bind<ICarRepository>().To<CarRepository>();

    }     

1 Ответ

0 голосов
/ 14 июня 2019

MVC требует без параметров.Если у вас нет конструктора, .Net-runtime автоматически создает конструкцию без параметров, в противном случае, если у вас конструирование с параметром, тогда среда выполнения этого не делает и выдает ошибку.

Ether вы создаете новый carService накаждый контроллер, или вы используете serviceProvider.Unittest просты с сервис-провайдером.С ядром asp.net это просто введите описание ссылки здесь , если вы используете mvc 4 или 5. вы можете увидеть здесь и посмотреть здесь образец введите описание ссылки здесь

...