对于学校,我们必须使用.NET实体核心框架编写自己的WebApi。我已经编写了api,但是当我试图用它挥舞时,它总是返回HTTP 500错误:内部服务器错误。我下载了Fiddler以开始调试,并在我的存储库中遇到了循环依赖项错误,但我不知道会在哪里发生。

接口(用于模拟测试)

public interface IVisitorRepository
{
    Visitor GetBy(string email);
    void AddVisitor(Visitor visitor);
    void SaveChanges();
}


具体课

public class VisitorRepository : IVisitorRepository
{
    private readonly ApplicationDbContext _context;
    private readonly DbSet<Visitor> _visitors;

    public VisitorRepository(ApplicationDbContext context, IVisitorRepository visitorRepository)
    {
        _context = context;
        _visitors = _context.Visitors;
    }

    public void AddVisitor(Visitor visitor)
    {
        _visitors.Add(visitor);
    }

    public Visitor GetBy(string email)
    {
        return _visitors.SingleOrDefault(v => v.Email == email);
    }

    public void SaveChanges()
    {
        _context.SaveChanges();
    }
}


我已经在我的管道中确定了范围。

这是一个基于JWT令牌的登录和注册api(这是我们需要做的),这是我的register方法(我正在测试的方法)

    [AllowAnonymous]
    [HttpPost("register")]
    public async Task<ActionResult<String>> Register(RegisterDTO model)
    {
        IdentityUser user = new IdentityUser { UserName = model.Email, Email = model.Email };
        Visitor visitor = new Visitor(model.FirstName + " " + model.LastName, model.Email, model.PhoneNumber, model.Country);
        var result = await _userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            _visitorRepository.AddVisitor(visitor);
            _visitorRepository.SaveChanges();
            string token = GetToken(user);
            return Created("", token);
        }
        return BadRequest();
    }


例外:


  InvalidOperationException:检测到类型为'DigitizedApi.Models.Repositories.IVisitorRepository'的服务的循环依赖关系。 DigitizedApi.Models.Repositories.IVisitorRepository(DigitizedApi.Data.Repositories.VisitorRepository)-> DigitizedApi.Models.Repositories.IVisitorRepository

最佳答案

问题是您的VisitorRepository(实现IVisitorRepository)对IVisitorRepository本身有依赖性。

实际上应该如下:

public class VisitorRepository : IVisitorRepository
{
    private readonly ApplicationDbContext _context;
    private readonly DbSet<Visitor> _visitors;

    public VisitorRepository(ApplicationDbContext context)
    {
        _context = context;
        _visitors = _context.Visitors;
    }
    .........
}

09-30 18:53