blazor作用域服务初始化两次 [英] blazor scoped service initializing twice

查看:467
本文介绍了blazor作用域服务初始化两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习asp.net核心,更具体地说是blazor服务器.从文档看来,注册为范围的服务将为每个连接创建一次.我的用户服务构造函数在浏览器中首次加载页面时运行两次,并在每次刷新页面时再次运行两次.

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>

推荐答案

在使用预渲染时,它被调用了两次.转到_Host.cshtml并将render-mode="ServerPrerendered"更改为render-mode="Server",它将仅被调用一次:

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>

参考:

https://docs.microsoft.com/zh-cn/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1#stateful-reconnection-after-prerendering

这篇关于blazor作用域服务初始化两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆