imjustaboy
imjustaboy

Reputation: 346

blazor scoped service initializing twice

I'm trying to learn asp.net core, more specifically blazor server. From the documentation, it appears a service registered as scoped will be created once per connection. My user service constructor is running twice on the first load of the page in the browser, and twice again on each refresh of the page.

I believe these are the applicable parts of the code necessary to help me determine why this is occurring. My question is how to make it create one instance of the user service for each client connection? I'm getting the correct output on screen but don't prefer it to run twice.

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddHttpContextAccessor();
    services.AddDbContext<AWMOPSContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("AWMOPSContext")),
        ServiceLifetime.Transient);
    services.AddScoped<UserService>();

}
public class UserService
{
    public Associate Associate { get; set; }

    public UserService(AWMOPSContext context, IHttpContextAccessor httpContextAccessor)
    {
        var username = httpContextAccessor.HttpContext.User.Identity.Name.Substring(7);
        Associate = context.Associates.Where(a => a.LogonName == username).FirstOrDefault();
        Debug.WriteLine($"Hello {Associate.PreferredName} {Associate.LastName}");
    }
}
@page "/"
@inject AWMWP.Services.UserService user;

<h1>Welcome @user.Associate.PreferredName @user.Associate.LastName</h1>

Upvotes: 5

Views: 4334

Answers (1)

Rena
Rena

Reputation: 36575

It is called twice, as you are using pre-rendering. Go to _Host.cshtml and change render-mode="ServerPrerendered" to render-mode="Server", and it would be called only once:

<app>
    <component type="typeof(App)" render-mode="Server" />
</app>

Reference:

https://learn.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1#stateful-reconnection-after-prerendering

Upvotes: 12

Related Questions