No parameterless constructor defined for this Object

Asked

Viewed 862 times

1

I am trying to create a constructor with parameters as shown below:

public class TestController : Controller
{
    private readonly IAppService _servico;

    public DashboardController(IAppService servico)
    {
        _servico = servico;
    }

    public ActionResult Index()
    {
        var a = _servico.Pesquisar();
        return View();
    }
}

Dependency injection was made, but still returns the error:

No parameterless constructor defined for this Object

   public static class SimpleInjectorWebApiInitializer
{

    public static void Initialize()
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new SimpleInjector.Lifestyles.AsyncScopedLifestyle();

        InitializeContainer(container);

        container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

        container.Verify();

        SimpleInjectorMvcExtensions.GetControllerTypesToRegister(container, Assembly.GetExecutingAssembly());
    }

    private static void InitializeContainer(Container container)
    {
        Bootstrapper.Start(container);
    }
}

I have tried several alternatives, but without success. You could tell me how to solve this problem?

Grateful from now on!

  • As the error itself indicates, you need to have a constructor that has no parameters, so just add public DashboardController() { }.

2 answers

3

No parameterless constructor defined for this Object

That is, you need to have a constructor without parameters:

public DashboardController()
{
}

This won’t disturb your other constructor with an interface where you’re injecting the dependency.

1


Missed you record the injection of dependency of the IAppService, your code would look something like this:

public static void Initialize()
{
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new SimpleInjector.Lifestyles.AsyncScopedLifestyle();

    //Registra os services
    container.Register<IAppService, AppService>(Lifestyle.Scoped);

    InitializeContainer(container); 

    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    container.Verify();

    SimpleInjectorMvcExtensions.GetControllerTypesToRegister(container, Assembly.GetExecutingAssembly());
}

You can see more in their documentation: https://simpleinjector.readthedocs.io/en/latest/mvcintegration.html

  • 1

    It worked, thank you very much for your help!!

Browser other questions tagged

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