c# - 使用我的存储库时无法解析类型的服务
问题描述
当我尝试访问我的存储库时,我收到一个错误:
InvalidOperationException:尝试激活“software.Notes.Http.Handlers.ShowNote”时无法解析“software.Notes.Repositories.NoteRepository”类型的服务。
所以,我有一个简单的 SoftwareContext:
public class SoftwareContext : DbContext
{
public SoftwareContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Contact> Contact { get; set; }
public DbSet<Note> Note { get; set; }
}
}
在我的 startup.cs 文件中实例化:
services.AddDbContext<SoftwareContext>(options =>
options.UseMySql(
Configuration.GetConnectionString("DefaultConnection")));
现在,我有一个简单的请求处理程序来显示注释:
[ApiController]
public class ShowNote : Controller
{
private readonly NoteRepository _note;
public ShowNote(NoteRepository note)
{
_note = note;
}
[HttpGet]
[Route("note/show/{id}")]
public IActionResult init(int id)
{
Note note = _note.Find(id);
if (note != null) {
return Ok(note);
}
return NotFound();
}
}
在我的存储库中,我有以下内容:
public abstract class NoteRepository : INoteRepository
{
private readonly SoftwareContext _context;
protected NoteRepository(SoftwareContext context)
{
_context = context;
}
public Note Create(Note note)
{
var add = _context.Note.Add(note);
return note;
}
public Note Find(int id)
{
return _context.Note.FirstOrDefault(x => x.Id.Equals(id));
}
}
不应该像我目前所做的那样通过我的存储库的构造函数注入上下文吗?有人可以解释为什么这不起作用,以及让它起作用的正确方法是什么?
完整的异常日志:
System.InvalidOperationException:尝试激活“software.Notes.Http.Handlers.ShowNote”时无法解析“software.Notes.Repositories.NoteRepository”类型的服务。在 Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.b__0 的 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) (ControllerContext controllerContext) 在 Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext) 在 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean&
解决方案
您必须将 NoteRepository 添加到 .NET Core 的 IOC 容器中。有三种方法可以做到这一点:在 startup.cs 类中添加
services.AddScoped<INoteRepository, NoteRepository>();
它将为每个请求创建一次 NoteRepository 类的实例
services.AddSingleton <INoteRepository, NoteRepository>();
这意味着您的 NoteRepository 类的实例将在请求之间共享
services.AddTransient <INoteRepository, NoteRepository>();
每次应用程序请求它时都会创建实例。
然后您可以通过控制器的构造函数注入依赖项
[ApiController]
public class ShowNote : Controller
{
private readonly INoteRepository _note;
public ShowNote(INoteRepository note)
{
_note = note;
}
}
推荐阅读
- angular - Angular 12,为什么路由器防护不起作用?
- javascript - 在 vuetify 小吃店中重置超时
- apache-spark - 在 Spark 3.1.1 java 中添加新列作为数组
- rxjs - Rxjs:等待外部可观察,将值传递给内部并在订阅中返回两个解析值
- java - 使用 tomcat 服务器在 Java 中创建一个简单的 API
- unit-testing - 使用匹配器返回 a 不能为空
- python - 尝试调整框架大小
- servlets - 我们如何根据优先级或顺序在一个 ServletContextListener 中启动多个服务/作业
- excel - 查找并复制整行并在当前行下方插入复制的行
- c++ - 重新分配 CComBSTR,内存泄漏?