问题
Service Registration
services.AddScoped(typeof(PageStorageService<>), typeof(PageStorageService<>));
Service Declaration
public interface IStoredPage<T>
{
T PageState { get; set; }
}
public class PageStorageService<T> : IStoredPage<T>
{
public T PageState { get; set; }
}
Usage in 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;
}
I have run multiple small tests like the one above)
And this Improvement to use OnInitialziedAsync ( an additional list was added to the counter class that is not shown )
@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();
}
This seems pretty clean and straight forward to me. But more eyes are generally better. It follows the same general pattern as the Local storage solutions i have seen (in my case I am only looking to store filters and tab selections for a dashboard type app -- I won't have large forms etc and I am more interested in the advantages of having page state in memory than the occasional server crash . The fact that it is injected as a service means any page that I want to use can opt In.. etc Thoughts, rocks, things I should have thought of?
来源:https://stackoverflow.com/questions/65044349/are-there-any-pitfalls-to-this-approach-which-i-am-not-seeing