3

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?

user3856437
  • 2,071
  • 4
  • 22
  • 27

1 Answers1

15

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.

ViRuSTriNiTy
  • 5,017
  • 2
  • 32
  • 58
codevision
  • 5,165
  • 38
  • 50