C
C#14mo 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'.'
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.
5 Replies
Pobiega
Pobiega14mo ago
you can't just create the scope, you must also resolve all services you need from the scoped service provider
Samuel
SamuelOP14mo ago
So I would have to provide the DbContext with the request?
jcotton42
jcotton4214mo ago
I think resolving the mediatr from the scoped provider will do it? you def don't need to include the dbcontext in the request
Pobiega
Pobiega14mo ago
yep mediatR will in turn request its handler from the same service provider, and thus the context from there too
Samuel
SamuelOP14mo ago
That did it! Final code:
private async void RequestAuctionDataProcessing(object? state)
{
await using var scope = _serviceProvider.CreateAsyncScope();
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
await mediator.Send(new ProcessAuctionDataCommand(1305));
}
private async void RequestAuctionDataProcessing(object? state)
{
await using var scope = _serviceProvider.CreateAsyncScope();
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
await mediator.Send(new ProcessAuctionDataCommand(1305));
}
Thanks @Pobiega and @jcotton42
Want results from more Discord servers?
Add your server