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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more