© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
7 replies
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'.'
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));
    }
}
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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

get scoped service
C#CC# / help
3y ago
✅ Cannot resolve scoped service...
C#CC# / help
4y ago
Issue with websocket within a service
C#CC# / help
2y ago