What's wrong in the dependency injection?

What’s wrong with my dependency injection? I followed C# tutorials, but it seems like I’m missing something.

HomeController

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly ICliente _cliente;

        public HomeController(ILogger<HomeController> logger, ICliente ClienteService)
        {
            _logger = logger;
            _cliente = ClienteService;
        }

ICliente

namespace Lanchonete.Interfaces
{
    public interface ICliente
    {
        public void TestarCliente();
    }
}

ClienteService

using Lanchonete.Interfaces;


namespace Lanchonete.Services
{
    public class ClienteService : ICliente
    {
        public void TestarCliente()
        {
            Console.WriteLine("TESTE OK");
        }
    }
}

Function using the ID

        public IActionResult Resposta(Produto produto)
        {
            _cliente.TestarCliente();
            return Redirect("/Home/Index");
        }

Program.cs

using Lanchonete.Interfaces;
using Lanchonete.Models;
using Lanchonete.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

builder.Services.AddTransient<ICliente, ClienteService>();

Error from the browser

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type ‘Lanchonete.Interfaces.ICliente’ while attempting to activate ‘Lanchonete.Controllers.HomeController’.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

>Solution :

You need add the service to the container before you invoke app.Run()

i.e.:

builder.Services.AddTransient<ICliente, ClienteService>(); // Move this here
app.Run();

Leave a Reply