C#C
C#3y ago
Samuel

✅ Using a scoped service within an IHostedService

I have a IHostedService implementation that sends a Mediatr request every hour. The handler uses a DbContext to carry out its work.

When sending the request, I get the following exception:
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Cannot resolve 'MediatR.IRequestHandler`1[AuctionData.Application.Features.ProcessAuctionData+ProcessAuctionDataCommand]' from root provider because it requires scoped service 'AuctionData.Application.Data.AuctionDbContext'.'


I have tried to create an async scope, but I still get the exception.
private async void RequestAuctionDataProcessing(object? state)
{
    await using (var scope = _serviceProvider.CreateAsyncScope())
    {
        await _mediator.Send(new ProcessAuctionDataCommand(1305));
    }
}


I have listed the project in GitHub. Here is a link to where the functionality lies https://github.com/Scharps/AuctionData/blob/Scharps/issue15/AuctionData.ApplicationCore/Features/ProcessAuctionData.cs

Thank you for reading.
Was this page helpful?