How to pass parameter to the constructor of a Controller?

2

How can I inject a parameter into the constructor of my Controller?

I have CategoriasController with a constructor that expects IAppServiceCategories appService , when I call it returns an error.

using ProjetoModelo.Application.Interfaces;
using ProjetoModelo.Domain.Entidades;
using ProjetoModelo.MVC.AutoMapper;
using ProjetoModelo.MVC.ViewModels;
using System.Collections.Generic;
using System.Web.Mvc;

namespace ProjetoModelo.MVC.Controllers
{
    public class CategoriasController : Controller
    {
        private readonly IAppServiceCategories _AppServiceCategories;

        public CategoriasController(IAppServiceCategories appService)
        {
            _AppServiceCategories = appService;
        }
        // GET: Categoria
        public ActionResult Index()
        {
            var categoriesViewModel = AutoMapperConfig.Mapper.Map<IEnumerable<Categories>, IEnumerable<CategoriesViewModel>>(_AppServiceCategories.GetAll());
            return View(categoriesViewModel);
        }
    }
}
  

Application Server Error '/'.

     

No parameterless constructor has been defined for this object.

     

Description: An unhandled exception occurred during the execution of the   current Web request. Examine the stack trace for   more information about the error and where it originated in the code.

     

Exception Details: System.MissingMethodException: No constructor   no parameters has been defined for this object.

     

Source Error:

     

Unhandled exception was generated during the execution of the current   information. The information relating to the origin and location of the   can be identified using the stack trace of   exception below.

     

Battery Tracking:

     

[MissingMethodException: No parameterless constructor has been 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)   +247 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   'ProjectModelo.MVC.Controllers.CategoriasController'. 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) +76
  System.Web.Mvc.DefaultControllerFactory.CreateController (RequestContext   requestContext, String controllerName) +88
  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 ()   +103 System.Web.HttpApplication.ExecuteStep (IExecutionStep step, Boolean & completedSynchronously) +155

     

Version Information: Microsoft .NET Framework Version: 4.0.30319;   ASP.NET Version: 04.7.2053.0

    
asked by anonymous 17.08.2017 / 17:48

1 answer

5

You need to install Dependency Injection (DI) framework in your project.

Unity for example.

Using Unity you need to register and map the concrete type that will be injected when you pass its interface ( IAppServiceCategories ) into controller constructor < in>).

Example:

// Cria uma instância do container de DI
var container = new UnityContainer(); 

// Registra o tipo concreto que será injetado
container.RegisterType<IAppServiceCategories, AppServiceCategories>();

You will need to create a class responsible for this configuration and in the Application_Start method of the Global.asax.cs file call the method to load this container . That is, by starting your application you already configure your dependencies in Unity container .

Some details are required to install and configure, so I recommend that you take a look at here .

    
17.08.2017 / 18:26