[英]InvalidOperationException: Cannot consume scoped service 'Microsoft.JSInterop.IJSRuntime' from singleton '...IAuthentication' in Blazor
I'm creating Blazor project that at first everything works fine until I need to inject IJSRuntime
into cs
file.我正在创建 Blazor 项目,起初一切正常,直到我需要将
IJSRuntime
注入cs
文件。
Microsoft.JSInterop;
...
...
public BaseService(IJSRuntime jSRuntime)
{
}
BaseService
is inherited in another service named AuthenticationServices
which is also uses an Interface called IAuthentication
. BaseService
在另一个名为AuthenticationServices
服务中继承,该服务也使用名为IAuthentication
的接口。 Thus因此
using Microsoft.JSInterop;
public class AuthenticationServices : BaseService, IAuthentication
{
public AuthenticationServices(IJSRuntime jSRuntime) : base(jSRuntime)
{
}
}
My issue is in Startup.cs
file which has this code我的问题是在具有此代码的
Startup.cs
文件中
services.AddSingleton<IAuthentication, AuthenticationServices>();
If I run the app it says,如果我运行该应用程序,它会说,
InvalidOperationException: Cannot consume scoped service 'Microsoft.JSInterop.IJSRuntime' from singleton '...IAuthentication'
What does it mean?这是什么意思? Am I doing it correctly that I only need something to add?
我是否正确地只需要添加一些东西?
Dependency injection in the Blazor has 3 different lifetime policies. Blazor 中的依赖注入有 3 种不同的生命周期策略。
This means that any service of that type will have only one instance.这意味着该类型的任何服务都将只有一个实例。
This lifetime mean that for set of object created scope
and within that scope will be just one instance.这个生命周期意味着对于一组对象创建的
scope
并且在该范围内将只有一个实例。 Usually in most scenarios, scope is created for processing User Session (Client-side Blazor) or User connection (Server-side Blazor).通常在大多数情况下,创建作用域是为了处理用户会话(客户端 Blazor)或用户连接(服务器端 Blazor)。 You can compare with scope per single HTTP request (ASP.NET).
您可以与每个 HTTP 请求 (ASP.NET) 的范围进行比较。
Object with this lifetime created each time they are requested.每次请求时都会创建具有此生命周期的对象。 It's same to regular
new
.与常规
new
相同。
Given the nature of these object lifetime policies, following rules for consuming services applies.鉴于这些对象生命周期策略的性质,以下用于使用服务的规则适用。
Transient
service can consume Transient,
Scoped and
Singleton` services. Transient
服务可以使用Transient,
Scoped and
Singleton` 服务。Scoped
service can consume Scoped
and Singleton
services. Scoped
服务可以使用Scoped
和Singleton
服务。 But cannot consume Transient
services.Transient
服务。Singleton
services can consume only Singleton
services. Singleton
服务只能使用Singleton
服务。 But cannot consume Transient
and Scoped
services.Transient
和Scoped
服务。 Service IJSRuntime
registered inside Blazor as Scoped
service, as such it can be used only by Scoped
and Transient
services.服务
IJSRuntime
在IJSRuntime
注册为Scoped
服务,因此它只能由Scoped
和Transient
服务使用。
So you either have to make AuthenticationServices
the Scoped
service, or get rid of IJSRuntime
as constructor parameter.因此,您要么必须使
AuthenticationServices
成为Scoped
服务,要么摆脱IJSRuntime
作为构造函数参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.