When injecting a controller dependency, Postman returns error

Asked

Viewed 63 times

0

By doing it in mine Controller:

[Route("api/[controller]")]
    public class OptOutClientController : Controller
    {
        IOptOutService _service;

        //Se comentar o construtor dá certo
        public OptOutClientController(IOptOutService service)
        {
            _service = service;
        }

        [HttpPost]
        public async Task<OptOutResult> Unsubscribe([FromBody]OptOutCliente cliente)
        {
            if (cliente == null)
                throw new OptOutException("Informar os dados do cliente OptOut!");

            var result = await _service.Process(new OptOutCliente(cliente.Cpf, cliente.Email, cliente.Telefone, cliente.Bandeira, cliente.Canal));

            return null;

        }

    }

I get a Internal Server Error (500) with the injection in the manufacturer. If I comment the constructor, then it works. What should I pass in Postman or in the service call to not receive this error?

inserir a descrição da imagem aqui

EDIT1

My Startup.cs:

public class Startup
{
     public void ConfigureServices(IServiceCollection services)
     {
         services.AddMvc();
         services.AddRouting();
     }

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "optoutroute",
                    template: "{controller=OptOutClient}/{action=Index}");
            });
     }
}

EDIT2

My Startup was like this method

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRouting();
            services.AddScoped<IOptOutService, ClientUnsubscribe>();
        }

My controller is like this

HttpClient client = new HttpClient();
        private readonly IOptOutService _service;
        public OptOutClientController(IOptOutService service)
        {
            _service = service;
        }
..........

At startup I tried: Scoped, Singleton, Transient, all cycles and continues with Server Error

  • @Leandroangelo, how would I do it? In which Startup method would I do it?

  • Take a look here. https://docs.microsoft.com/pt-br/aspnet/corefundamentals/dependency-injection?view=aspnetcore-2.1 and here https://docs.microsoft.com/pt-br/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-2.1

1 answer

1


You need to declare this Ioptoutservice dependency in the Configureservices method of the Startup class.

services.addScoped<IOptOutService, SuaImplementacao>();
  • In the maeod I switched from Frombody to Fromservices and nothing yet

  • The error was in the class that implements the interface.

Browser other questions tagged

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