How to pass parameter to a Controller constructor?

Asked

Viewed 639 times

2

How can I inject a parameter into my Controller constructor?

I have the CategoriasController with a builder waiting for the IAppServiceCategories appService, When I call a mistake returns to me.

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

Server Error in Application '/'.

No constructor without parameters has been defined for this object.

Description: An untreated exception occurred during the execution of current web request. Examine stack tracking to get more information about the error and where it originated in the code.

Exception Details: System.Missingmethodexception: No constructor no parameters has been set for this object.

Error of Origin:

Untreated exception was generated during the current execution web request. The information related to the origin and location of the exception can be identified by using stack tracking exception below.

Cell Trace:

[Missingmethodexception: No constructor without parameters 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 'Projectmodel.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:4.7.2053.0

  • I do not know where I went wrong in the question, but if you have to supplement, let me know by giving a -1.

1 answer

5


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

The Unity for example.

Using the Unity you need to record and map the concrete type that will be injected when you pass your interface (Iappservicecategories) in the controller constructor (Categoriascontroller).

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 method Application_start of the archive Global.asax.Cs call the method to load this configuration from container. That is, starting your application you already configure in Unity container its dependencies.

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

  • cool, vlw.....

  • If you are using Asp Net Core it already comes with its own dependency injector, then just sign in the Configuraeservices method of the Startup class. TIP!!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.