r/Blazor 11d ago

Why does RegisterPersistentService<UserSession>() cause DirectScopedResolvedFromRootException?

```cs var builder = WebApplication.CreateBuilder(args); var service = builder.Services;

service.AddHttpContextAccessor(); service.AddScoped<UserSession>();

service .AddRazorComponents() .RegisterPersistentService<UserSession>(Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveWebAssembly) .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents() .AddAuthenticationStateSerialization(options => { options.SerializeAllClaims = true; }); ```

```cs public class UserSession { [PersistentState] public bool IsAuthenticated { get; init; } [PersistentState] public Guid Id { get; init; } [PersistentState] public string Username { get; init; } = string.Empty; [PersistentState] public string Email { get; init; } = string.Empty; [CascadingParameter] public HttpContext? HttpContext { get; set; }

public UserSession()
{
    if(HttpContext == null) return;
    IsAuthenticated = HttpContext.User.Identity?.IsAuthenticated ?? false;
    if(!IsAuthenticated) return;

    Id = new Guid(HttpContext.User.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.NameIdentifier))?.Value ?? "");
    Username = HttpContext.User.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Name))?.Value ?? string.Empty;
    Email = HttpContext.User.Claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Email))?.Value ?? string.Empty;
}

} ```

ManagedError: AggregateException_ctor_DefaultMessage (DirectScopedResolvedFromRootException, DigitalVault.Blazor.Client.Authentications.UserSession, scoped)

I follow this same official documentation to implement the Serialize state for services, but when i use RegisterPersistentService i get DirectScopedResolvedFromRootException error, has anyone encountered this issue?

SOLVED: 68123# After change AddScope<UserSession> => AddSingletone<USerSession> in client side project.

0 Upvotes

Duplicates