I have a Blazor-service that needs a specific "LocalStorage"-service injected. It is done this way:
public class UserApi : IUserApi
{
private readonly LocalStorage _localStorage;
public UserApi(LocalStorage localStorage)
{
_localStorage = localStorage;
}
...
}
"LocalStorage" is injected within the Startup.cs (ConfigureServices):
services.AddStorage();
(I think it is safe to assume that this works as it should)
I also added my own service with the following line:
services.AddSingleton<IUserApi, UserApi>();
On the razor-page I inject my Service:
@inject IUserApi UserApi
and access a function there:
private void HandleValidSubmit()
{
if (UserApi.Login( _loginUser.Mail, _loginUser.Password, out string error, out Guid? guid))
{
// DoMagic
}
}
When I try to start my application I receive the following error:
System.AggregateException
Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: BlazorFood.IUserApi Lifetime: Singleton ImplementationType: BlazorFood.UserApi': Cannot consume scoped service 'Cloudcrate.AspNetCore.Blazor.Browser.Storage.LocalStorage' from singleton 'BlazorFood.IUserApi'.
Inner Exception 2: InvalidOperationException: Cannot consume scoped service 'Cloudcrate.AspNetCore.Blazor.Browser.Storage.LocalStorage' from singleton 'BlazorFood.IUserApi'
When I remove the AddSingleton-line from ConfigureServices I can start my application but retrieve an error when trying to access the razor-page containing the IUserApi-Injection:
InvalidOperationException: Cannot provide a value for property 'UserApi' on type 'BlazorFood.Pages.admin.Login'. There is no registered service of type 'BlazorFood.IUserApi'
What has to be done to inject my services properly?