简体   繁体   中英

C# - Controller can't see service

Controller cannot see Service . When I push add request on my API, it gives me code 500 error this is error => code:500 error
Can anyone help me?

Controller >

 

     [ApiController]
     [Route("[controller]")]
     public class ToDosController:Controller
     {
        IToDoService service;

        public ToDosController(IToDoService _service)
        {
            service = _service;
        }


        [HttpPost]
        public void Add(ToDo toDo)
        {
            service.Add(toDo);
        }

    

Service >


    public class ToDoService : IToDoService
      {
        IToDoFW database;

        public ToDoService(IToDoFW _database)
        {
            this.database = _database;
        }
        public void Add(ToDo toDo)
        {
            database.Add(toDo);
        }
      }


This is my program.cs codes:


    var builder = WebApplication.CreateBuilder(args);
 
    // Add services to the container.
    builder.Services.AddControllers();

    // Learn more about configuring Swagger/OpenAPI at 
    https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    builder.Services.AddDbContext<ToDoContext>();
    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
      app.UseSwagger();
      app.UseSwaggerUI();
    }
    IServiceCollection services;
    app.UseHttpsRedirection();

    app.UseAuthorization();

    app.MapControllers();

    app.Run();



Fw it means that FrameWork. . . . I hope you can help me about it, thanks for reading guys

You have to add the service to your IServiceCollection in your Program.cs (for .NET6 and higher) or Startup.cs (.NET 5.0 and lower).

services.AddScoped<IToDoService, ToDoService>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM