Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

What is the correct way to use dbContext in Blazor server NavMenu.razor component?

$
0
0

I have a default template project, .net 8, server rendering. In this project there is a NavMenu.razor component. My goal is to add menu new items when the user is authorized. Here is what I do:

I have following services registered:

builder.Services.AddDbContext<LuahDbContext>(options =>                                        options.UseSqlite($"Data Source={builder.Configuration["db"]}"));builder.Services.AddSingleton<LuahAuthService>();builder.Services.AddScoped<ScheduleOps>();

NavMenu structure (I am not showing standard Microsoft packages):

@inject IServiceProvider ServiceProvider@inject ScheduleOps ScheduleOps@inject MenuService MenuService@inject LuahAuthService AuthService

In the code section of NavMenu.razor component I have:protected override Task OnAfterRenderAsync(bool firstRender){if (firstRender)AuthService.OnChange += HandleMenuChangeAsync;return base.OnAfterRenderAsync(firstRender);}

private async Task HandleMenuChangeAsync(){    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();    if (!authState.User.Identity.IsAuthenticated)        return;    var userid = authState.User.FindFirst("userid").Value;    List<Schedule> lst = null;    try    {        using (var scope = ServiceProvider.CreateScope())        {            lst = await scope.ServiceProvider.GetRequiredService<ScheduleOps>().CustomerSchedules(userid);        }    }    catch (Exception ex)    {        Console.WriteLine(ex.Message);    }}

The exception is thrown in the line

        lst = await scope.ServiceProvider.GetRequiredService<ScheduleOps>().CustomerSchedules(userid);

and it is:System.ObjectDisposedException: 'Cannot access a disposed object.Object name: 'IServiceProvider'.'

This is my latest attempt. First attempt was to use injected service ScheduleOps directly. It also accepts dbContext as a constructor parameter, managed by DI, and the error was of the same type: expired dbContext.

My question is - what I am doing wrong? Services are scoped and blazor should manage the lifecycle of these components, right? I am confused.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>