Reputation: 13
Controller cannot see Service. When I push add request on my API, it gives me code 500 error. This is 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
means that FrameWork
. . . . I hope you can help me about it , thanks for reading guys
Upvotes: 1
Views: 136
Reputation: 563
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>();
Upvotes: 4