Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.csfile 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?

like image 741
user3856437 Avatar asked Oct 21 '25 16:10

user3856437


1 Answers

Dependency injection in the Blazor has 3 different lifetime policies.

  • Singleton
  • Scope
  • Transient

Singleton

This means that any service of that type will have only one instance.

Scope

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).

Transient

Object with this lifetime created each time they are requested. It's same to regular new.

Lifetime consumption rules

Given the nature of these object lifetime policies, following rules for consuming services applies.

  • Transient service can consume Transient, ScopedandSingleton` 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.

like image 163
codevision Avatar answered Oct 23 '25 05:10

codevision



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!