【发布时间】:2020-01-27 10:28:56
【问题描述】:
我曾经在 MVC Application 中有一个公共服务,将其注册为 Transient 服务并在整个应用程序中访问它的值而没有任何问题。
我尝试在客户端 Blazor 应用程序中实现相同的机制
首先创建了一个类AppState
public class AppState
{
public string BaseUrl { get; set; }
}
注册为服务
services.AddSingleton<AppState, AppState>();
用于 Blazor 组件索引组件
public class IndexComponent : ComponentBase
{
[Inject]
HttpClient Http { get; set; }
[Inject]
public AppState AppState { get; set; }
protected override async Task OnInitializedAsync()
{
AppState = await Http.GetJsonAsync<AppState>(ConfigFiles.GetPath("appsettings.json"));
await Task.FromResult(0);
}
}
试图在 index.razor 文件中打印 base url
@page "/"
@inherits IndexComponent
<p>@AppState.BaseUrl</p>
到这里为止很好,现在因为它包含基本 url,所以我想在另一个组件中访问它
public class MiniCartComponent : ComponentBase
{
[Inject]
public AppState AppState { get; set; }
protected override async Task OnInitializedAsync()
{
await Task.FromResult(0);
}
}
这里是空的,我不知道为什么
我尝试在剃须刀文件中打印它
@inherits MiniCartComponent
<p>@AppState.BaseUrl</p>
这里是空的,它被注册为跨组件共享数据的服务,一旦设置它不应该在整个应用程序中具有价值吗??
【问题讨论】:
-
将 AppState = await Http.GetJsonAsync
(ConfigFiles.GetPath("appsettings.json")); 更改为 var appState = await Http.GetJsonAsync(ConfigFiles.GetPath("appsettings.json")); AppState.BaseUrl = appState.BaseUrl; -
好吧,它成功了,它背后的概念是什么。以后json文件里会有很多key,我得这样一一设置
-
只修改AppState,不要设置其他值。如果有很多字段,只需将其包装到其他类。
-
好的,但是在 AppState.BaseUrl = appState.BaseUrl; 之后它是如何工作的,你能澄清一下吗
-
您将 AppState 注册为单例,我将其称为实例 A,当您将其注入组件时,它仍然是实例 A,并且您在组件中使用 API 的结果设置 AppState,它将是实例 B,对实例 A。
标签: .net-core blazor blazor-server-side .net-core-3.0 blazor-client-side