C#
C#

help

Root Question Message

Foxtrek_64
Foxtrek_648/15/2022
ServiceProvider not providing registered service [Answered]

For some reason, despite registering this api wrapper as so:
services.TryAddScoped<IInContactRestAPI>
(
    serviceProvider => new InContactRestAPI
    (
        serviceProvider.GetRequiredService<IRestHttpClient>(),
        serviceProvider.GetRequiredService<IOptionsMonitor<JsonSerializerOptions>>().Get(InContact),
        serviceProvider.GetRequiredService<IOptions<InContactConfig>>(),
        serviceProvider.GetRequiredService<ITokenStore>()
    )
);

Attempting to retrieve it from the service provider results in an InvalidOperationException because the type is not in the service provider. This happens whether I request the interface or the concrete implementation. Rider does in fact confirm that the scoped rest api wrapper is present in the service collection when stepping through.
Foxtrek_64
Foxtrek_648/15/2022
In the screeshotted sample above, I changed GetRequiredService() to GetService() to avoid the throw since I'm using a result mechanism, but as you can see it hits the return Result.FromError() line because the returned service instance is null.
Tvde1
Tvde18/15/2022
how are you retrieving it from the service provider?
Tvde1
Tvde18/15/2022
you are retrieving the IInContactRestAPI, right?
Tvde1
Tvde18/15/2022
be sure to create a scope
Foxtrek_64
Foxtrek_648/15/2022
var restApi = serviceProvider.GetService<IInContactRestAPI>();
if (restApi is null)
{
    return Result.FromError
        (new InvalidOperationError($"Unable to retrieve an instance of {nameof(InContactRestAPI)}"));
}
Foxtrek_64
Foxtrek_648/15/2022
You know what, that might be it entirely. I don't know if the plugin service creates a scope per plugin
Tvde1
Tvde18/15/2022
you need to do
using var scope = serviceProvider.CreateScope();
var restApi = scope.ServiceProvider.GetService<IInContactRestAPI>();
Tvde1
Tvde18/15/2022
typed that without intellisense so I don't know if it's correct
Foxtrek_64
Foxtrek_648/15/2022
Foxtrek_64
Foxtrek_648/15/2022
Looks like it's happy now
Tvde1
Tvde18/15/2022
😁
Foxtrek_64
Foxtrek_648/15/2022
await using var serviceScope = serviceProvider.CreateAsyncScope();
var restApi = serviceScope.ServiceProvider.GetService<IInContactRestAPI>();
if (restApi is null)
{
    return Result.FromError
        (new InvalidOperationError($"Unable to retrieve an instance of {nameof(InContactRestAPI)}"));
}
Tvde1
Tvde18/15/2022
async scope, fancy
Foxtrek_64
Foxtrek_648/15/2022
I'll add that as an issue to the plugin library I think. Plugins should have their own scopes.
Tvde1
Tvde18/15/2022
You can /close it if it all works ^^
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy