问题描述
我有一个Blazor服务,需要注入特定的"LocalStorage"服务.这样做是这样的:
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"注入到Startup.cs( ConfigureServices
)中:
"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
并在那里访问功能
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:
内部异常1:
InvalidOperationException:验证服务时出错描述符'ServiceType:BlazorFood.IUserApi生存期:单例ImplementationType:BlazorFood.UserApi':无法使用作用域服务来自的"Cloudcrate.AspNetCore.Blazor.Browser.Storage.LocalStorage"单例"BlazorFood.IUserApi".
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'.
内部异常2:InvalidOperationException:无法使用作用域服务'Cloudcrate.AspNetCore.Blazor.Browser.Storage.LocalStorage'来自单例"BlazorFood.IUserApi"
Inner Exception 2: InvalidOperationException: Cannot consume scoped service 'Cloudcrate.AspNetCore.Blazor.Browser.Storage.LocalStorage' from singleton 'BlazorFood.IUserApi'
当我从 ConfigureServices
删除AddSingleton-line时,我可以启动我的应用程序,但尝试访问包含IUserApi-Injection的剃刀页面时检索到错误:
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:
要正确注入我的服务需要做什么?
What has to be done to inject my services properly?
推荐答案
这部分错误消息
从文档中也可以看到
注册时不要让您的服务单身,这应该可以解决问题
Don't make your service singleton when registering it and that should fix the issue
services.AddScoped<IUserApi, UserApi>();
这篇关于如何在Blazor Server的后端中正确使用依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!