I'm creating Blazor project that at first everything works fine until I need to inject IJSRuntime
into cs
file.
Microsoft.JSInterop;
...
...
public BaseService(IJSRuntime jSRuntime)
{
}
BaseService
is inherited in another service named AuthenticationServices
which is also uses an Interface called 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
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.
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. Usually in most scenarios, scope is created for processing User Session (Client-side Blazor) or User connection (Server-side Blazor). You can compare with scope per single HTTP request (ASP.NET).
Object with this lifetime created each time they are requested. It's same to regular new
.
Given the nature of these object lifetime policies, following rules for consuming services applies.
Transient
service can consume Transient,
Scoped and
Singleton` services. Scoped
service can consume Scoped
and Singleton
services. But cannot consume Transient
services.Singleton
services can consume only Singleton
services. But cannot consume Transient
and Scoped
services. Service IJSRuntime
registered inside Blazor as Scoped
service, as such it can be used only by Scoped
and Transient
services.
So you either have to make AuthenticationServices
the Scoped
service, or get rid of IJSRuntime
as constructor parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.