DEV Community

Mario Diaz
Mario Diaz

Posted on

How I solved .NET error: A circular dependency was detected for the service of type

I was facing an error in an app that I took with some design problems and trying to do some things when we needed to add new features and solve bugs, this error was:

"Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: IMyService Lifetime: Scoped ImplementationType: MyService': A circular dependency was detected for the service of type 'Interfaces.IMyService'.\r\nInterfaces.IMyService(Services.MyService) -> Interfaces.IMyService(Services.MyService) -> Interfaces.IMyServiceService(Services.MyService) -> Interfaces.IMyService(Services.MyService) -> Interfaces.IMyService(Services.MyService) -> Interfaces.IMyService) (Error while validating the service descriptor 'ServiceType: Interfaces.IMyService Lifetime: Scoped ImplementationType: Services.MyService': A circular dependency was detected for the servi..." string

The solution I found was this:
Creating a class member:
private readonly IServiceProvider _serviceProvider;

Inject this in the class constructor:
public MyService(
IServiceProvider serviceProvider,
// Other injections ...
)
{
_serviceProvider = serviceProvider;
}

In the place we need to use the service:

var scope = _serviceProvider.CreateScope();
IMyService _myService = scope.ServiceProvider.GetRequiredService<IMyService>();
await _myService .TheMethod()

If you have any other solution, please let me know!

Top comments (0)