首页 > 解决方案 > Blazor 服务器:在 App.razor 中初始化的 Scoped 服务在 Page 中为空

问题描述

我在 blazor 服务器应用程序中使用这个 App.razor:

    <CascadingValue Name="SessionID" Value="SessionID" TValue="Guid">
    <CascadingAuthenticationState>
        <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, theres nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
    </CascadingAuthenticationState>
</CascadingValue>
@code {

    [Parameter] public Guid SessionID { get; set; }


    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        sessionID.SessionID = SessionID;

        cart = mySingleton.Get<Cart>(sessionID.SessionID) ?? new Cart(); // breakpoint (after page refresh) cart is set

    }
}

然后在页面中我有这个:

    @if (cart != null) // breakpoint executed next, cart is empty
{
    <br />
    <label><b>Cart Items:</b></label>
    <br />
    @foreach (var item in cart.lineCollection)
    {
        @item.PColor.displayValue
        <br />
        @item.PLabel.First().displayValue
        <hr />
    }
}

我将作用域服务注入到主 _Imports.razor 文件中的所有组件中:

@inject MySingleton mySingleton
@inject MyScopedSessionID sessionID
@inject Cart cart 

购物车作为范围服务注入。当我调试它时(在填充购物车并刷新页面之后),首先,应用程序被执行并且购物车被正确设置了一个带有一些项目的购物车对象,然后页面被执行,但是购物车是空的并且页面上没有任何内容, 为什么会发生这种情况以及如何纠正这种情况?

编辑:

我意识到不应该完全分配服务,我创建了一个带有 Cart 属性的 Scoped 服务,然后分配了这个属性,现在可以工作了。

标签: c#asp.net-coreblazor-server-side

解决方案


推荐阅读