Search code examples
c#.netentity-framework-coreasp.net-core-webapi

Circular dependency in ASP.NET Core


For school we have to write our own WebApi using the .NET Entity Core Framework. I've written my API but when I tried to use it in swagger, it always returned a HTTP 500 error: internal server error. I downloaded Fiddler to start debugging and came across a circular dependency error in my repository but I can't figure out where this would take place.

The interface (for mock testing)

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

The concrete class

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();
    }
}

I've scoped it in my pipeline.

It's a JWT token based login and register API (that's what we need to make) and here's my register method (the method I'm testing):

[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();
}

The exception:

InvalidOperationException: A circular dependency was detected for the service of type 'DigitizedApi.Models.Repositories.IVisitorRepository'. DigitizedApi.Models.Repositories.IVisitorRepository(DigitizedApi.Data.Repositories.VisitorRepository) -> DigitizedApi.Models.Repositories.IVisitorRepository


Solution

  • Problem is your VisitorRepository (which implements IVisitorRepository) has a dependency on IVisitorRepository itself.

    Actually it should be as follows:

    public class VisitorRepository : IVisitorRepository 
    {
        private readonly ApplicationDbContext _context;
        private readonly DbSet<Visitor> _visitors;
    
        public VisitorRepository(ApplicationDbContext context) 
        {
            _context = context;
            _visitors = _context.Visitors;
        }
        .........
    }