I have two classes, AccountService:
public class AccountService : IAccountService
{
private readonly UserManager<CustomIdentityUser> _userManager;
private readonly SignInManager<CustomIdentityUser> _signInManager;
private readonly RoleManager<CustomIdentityRole> _roleManager;
private readonly IUserRepository _userRepository;
private readonly LinkGenerator _linkGenerator;
private readonly IHttpContextAccessor _accessor;
private readonly IMediaService _mediaService;
public AccountService(
UserManager<CustomIdentityUser> userManager,
SignInManager<CustomIdentityUser> signInManager,
LinkGenerator linkGenerator,
IHttpContextAccessor accessor,
IMediaService mediaService,
RoleManager<CustomIdentityRole> roleManager,
IUserRepository userRepository)
{
_userManager = userManager;
_signInManager = signInManager;
_linkGenerator = linkGenerator;
_accessor = accessor;
_mediaService = mediaService;
_roleManager = roleManager;
_userRepository = userRepository;
}
and the other called MediaService:
public class MediaService : IMediaService
{
private readonly IMediaRepository _mediaRepository;
private readonly IAccountService _accountService;
private readonly IHttpContextAccessor _accessor;
public MediaService(
IMediaRepository mediaRepository,
IAccountService accountService,
IHttpContextAccessor accessor)
{
_mediaRepository = mediaRepository;
_accountService = accountService;
_accessor = accessor;
}
}
I injected these two into the IoC layer to use:
services.AddScoped<IMediaService, MediaService>();
services.AddScoped<IAccountService, AccountService>();
But I get an error at runtime:
Error while validating the service descriptor 'ServiceType: Aroma_Shop.Application.Interfaces.IMediaService Lifetime: Scoped ImplementationType: Aroma_Shop.Application.Services.MediaService': A circular dependency was detected for the service of type 'Aroma_Shop.Application.Interfaces.IMediaService'.
Aroma_Shop.Application.Interfaces.IMediaService(Aroma_Shop.Application.Services.MediaService) -> Aroma_Shop.Application.Interfaces.IAccountService(Aroma_Shop.Application.Services.AccountService) -> Aroma_Shop.Application.Interfaces.IMediaService"}
I understand where the problem is, if you look at the two classes AccountService and MediaService, you will notice that within each of these two classes, I requested to inject the other class. In AccountService I requested from service to inject MediaService, and in MediaService I requested from service to inject AccountService
The service descriptor can't inject these two classes, because when it wants to inject AccountService, it needs a MediaService to generate an object from it, and when it wants to inject MediaService, it needs AccountService to generate an object from it.
If possible, please help me solve this problem. Thanks a lot.