Blazor server scoped service is different

219 Views Asked by At

I need to store the authenticated user Session Id, where access token is retrieved from dictionary per user session.

I have simple Scoped service services.AddScoped<SessionService>();

public class SessionService
{
    public string SessionId { get; set; }
}

In MainLayout.razor I'm injecting it and setting it when the user log in. Which works fine.

@inject SessionService SessionService

.....

@code {
  [CascadingParameter]
  private Task<AuthenticationState> AuthenticationStateTask { get; set; }

  protected override async Task OnInitializedAsync() 
  {
      SessionService.SessionId = (await AuthenticationStateTask).User.GetSessionId();
  }
}

However, I'm creating HttpClient from IHttpClientFactory and getting the access token based on the user Session Id, but all 3 different approaches to get the SessionService have SessionId set to null

services.AddHttpClient("backend", async (provider, client) =>
        {
            var httpContextAccessor = provider.GetService<IHttpContextAccessor>();
            var httpContextService = httpContextAccessor.HttpContext.RequestServices.GetService<SessionService>();
            using var scope = provider.CreateScope();
            var anotherProvider = services.BuildServiceProvider();
            var anotherSession = anotherProvider.GetService<SessionService>();
            var sessionId = scope.ServiceProvider.GetService<SessionService>()?.SessionId;
            client.BaseAddress = ...;
        });

If I use the service inside component the SessionId is what it has to be and not null. Why is that happening and how to fix it?

0

There are 0 best solutions below