我正在尝试构建一个简单的 api 作为对项目未来 api 的测试。但我一直有这个错误
InvalidOperationException:尝试激活“AspnetCore_WebApi.Models.TarefaRepositorio”时,无法解析“AspnetCore_WebApi.Models.TarefaContext”类型的服务。
这是 TarefaContext.cs
using Microsoft.EntityFrameworkCore;
namespace AspnetCore_WebApi.Models
{
public class TarefaContext : DbContext
{
public TarefaContext(DbContextOptions<TarefaContext> options)
: base(options)
{ }
public DbSet<TarefaItem> TarefaItens { get; set; }
}
}
TarefaRepositorio.cs
using System.Collections.Generic;
using System.Linq;
namespace AspnetCore_WebApi.Models
{
public class TarefaRepositorio : ITarefaRepositorio
{
private readonly TarefaContext _context;
public TarefaRepositorio(TarefaContext context)
{
_context = context;
Add(new TarefaItem { Nome = "Item1" });
}
public IEnumerable<TarefaItem> GetAll()
{
return _context.TarefaItens.ToList();
}
public void Add(TarefaItem item)
{
_context.TarefaItens.Add(item);
_context.SaveChanges();
}
public TarefaItem Find(long key)
{
return _context.TarefaItens.FirstOrDefault(t => t.Chave == key);
}
public void Remove(long key)
{
var entity = _context.TarefaItens.First(t => t.Chave == key);
_context.TarefaItens.Remove(entity);
_context.SaveChanges();
}
public void Update(TarefaItem item)
{
_context.TarefaItens.Update(item);
_context.SaveChanges();
}
}
}
TarefaController.cs
using System.Collections.Generic;
using AspnetCore_WebApi.Models;
using Microsoft.AspNetCore.Mvc;
namespace AspnetCore_WebApi.Controllers
{
[Route("api/[controller]")]
public class TarefaController : Controller
{
private readonly ITarefaRepositorio _tarefaRepositorio;
public TarefaController(ITarefaRepositorio tarefaRepositorio)
{
_tarefaRepositorio = tarefaRepositorio;
}
[HttpGet]
public IEnumerable<TarefaItem> GetAll()
{
return _tarefaRepositorio.GetAll();
}
[HttpGet("{id}", Name = "GetTarefa")]
public IActionResult GetById(long id)
{
var item = _tarefaRepositorio.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
[HttpPost]
public IActionResult Create([FromBody] TarefaItem item)
{
if (item == null)
{
return BadRequest();
}
_tarefaRepositorio.Add(item);
return CreatedAtRoute("GetTarefa", new { id = item.Chave }, item);
}
}
}
ITarefaRepositorio.cs
using System.Collections.Generic;
namespace AspnetCore_WebApi.Models
{
public interface ITarefaRepositorio
{
void Add(TarefaItem item);
IEnumerable<TarefaItem> GetAll();
TarefaItem Find(long key);
void Remove(long key);
void Update(TarefaItem item);
}
}