首页 > 解决方案 > 使用我的存储库时无法解析类型的服务

问题描述

当我尝试访问我的存储库时,我收到一个错误:

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&

标签: c#asp.net-mvcasp.net-web-apiasp.net-core

解决方案


您必须将 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;
    }
}

推荐阅读