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!

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more