c# - 这种方法有没有我没有看到的陷阱
问题描述
服务注册
services.AddScoped(typeof(PageStorageService<>), typeof(PageStorageService<>));
服务声明
public interface IStoredPage<T>
{
T PageState { get; set; }
}
public class PageStorageService<T> : IStoredPage<T>
{
public T PageState { get; set; }
}
CounterPage 中的用法
@page "/counter"
@using BlazorApp1.Data
<h1>Counter</h1>
<p>Current count: @currentCount</p>
@inject PageStorageService<Counter> StorageService
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
protected override async Task OnParametersSetAsync()
{
// reset what we want from stored copy
if (StorageService.PageState != null)
{
currentCount = StorageService.PageState.currentCount;
}
//reconnect for this page lifespan we have a reference copy of the pages class
// which is copied into the service Or so experimentation seems to indicate
StorageService.PageState = this;
}
我已经运行了多个小测试,例如上面的测试)
以及使用 OnInitialziedAsync 的改进(在未显示的计数器类中添加了一个附加列表)
@using BlazorApp1.Data
<h1>Counter2</h1>
<p>Current count: @currentCount</p>
<p>PageStateNull : @PageStateNullCount</p>
<div> @((MarkupString)string.Join("\r\n", TestDataSave)) </div>
@inject PageStorageService<Counter2> StorageService
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int PageStateNullCount = 0;
private List<string> TestDataSave;
private int currentCount = 0;
private void IncrementCount()
{
TestDataSave.Add("<div>count before Inc : " + currentCount.ToString() + "</div>");
currentCount++;
TestDataSave.Add("<div>count after Inc :" + currentCount.ToString() + "<div>");
}
protected override Task OnInitializedAsync()
{
// reset what we want from stored copy
if (StorageService.PageState != null)
{
currentCount = StorageService.PageState.currentCount;
TestDataSave = StorageService.PageState.TestDataSave;
PageStateNullCount = StorageService.PageState.PageStateNullCount;
}
else
{
PageStateNullCount++;
//create for the first time aka read from database
TestDataSave = new List<string>();
TestDataSave.Add("<div>OnParametersSetAsync</div>");
}
//reconnect
StorageService.PageState = this;
return base.OnInitializedAsync();
}
这对我来说似乎很干净而且很直接。但是更多的眼睛通常更好。它遵循与我见过的本地存储解决方案相同的一般模式(在我的情况下,我只想存储仪表板类型应用程序的过滤器和选项卡选择——我不会有大型表单等,我对与偶尔的服务器崩溃相比,在内存中拥有页面状态的优势。它作为服务注入的事实意味着我想使用的任何页面都可以选择加入..等想法,岩石,我应该想到的事情?
解决方案
推荐阅读
- python - 根据列的最小值选择两列值
- python - 在 django 中编写自定义重定向装饰器
- kdb - kdb:如何在控制台中显示整个列表?
- python - 如何替换字符串中的空格逗号?
- assembly - 使用动态链接 libc 开始调试 32 位 ARM 程序集时 gdb 挂起
- android - Android Preferences DataStore 与现有 Room 实现
- apache - 如何让 Apache 将 Web 应用程序作为根文档提供服务?
- javascript - ReactJS:按钮(跨度)视觉应该在单击时重新渲染和更改,但不会(使用 setState)
- apache-spark - PySpark-在独立集群模式下运行时访问 udf 中的广播变量时出错
- .net - 以 .Net 框架为目标时消除程序集绑定重定向