Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception: Cannot resolve scoped service from root provider

I've created a console application that runs as a Windows service. It's also using Hangfire to trigger my code.

That is all working fine. But for testing, I just want to be able to just run it on my development machine, create whatever classes I need and make full use of dependency injection.

So I added a test background service.

services.AddHostedService<TestBackgroundService>();

services.AddScoped<IReportBuilderWorkerService, ReportBuilderWorkerService>();

And here's my TestBackgroundService class.

class TestBackgroundService : BackgroundService
{
    public IServiceProvider ServiceProvider { get; }

    public TestBackgroundService(IServiceProvider serviceProvider)
    {
        ServiceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        IReportBuilderWorkerService builder = ServiceProvider.GetRequiredService<IReportBuilderWorkerService>();
        await builder.RunAsync(1);

        Environment.Exit(0);
    }
}

But when I run the line ServiceProvider.GetRequiredService<IReportBuilderWorkerService>(), it throws an exception:

System.InvalidOperationException: 'Cannot resolve scoped service 'WorkerServicesCommon.IReportBuilderWorkerService' from root provider.'

All I want to do is temporarily run some test code. But I need to do it in a way that dependency injection is fully available. Can anyone help?

like image 977
Jonathan Wood Avatar asked Jan 22 '26 10:01

Jonathan Wood


1 Answers

Scoped services should be initiated in a scope

    using (var scope = ServiceProvider.CreateScope())
    {
        var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>();
        // your usual code
    }

The logic of a scope relates to a unit of work or execution context. If you don't need a fresh copy every time, you can do AddSingleton since it seems your service doesn't depend on anything. This way you have a static instance initiated only once.

like image 159
Candide Avatar answered Jan 23 '26 22:01

Candide



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!