PreserveStateService.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. using Microsoft.AspNetCore.Components;
  4. using Microsoft.AspNetCore.Components.Web;
  5. namespace BasicTestApp;
  6. public class PreserveStateService : IDisposable
  7. {
  8. private readonly PersistentComponentState _componentApplicationState;
  9. private PersistingComponentStateSubscription _persistingSubscription;
  10. private ServiceState _state = new();
  11. public PreserveStateService(PersistentComponentState componentApplicationState)
  12. {
  13. _componentApplicationState = componentApplicationState;
  14. _persistingSubscription = _componentApplicationState.RegisterOnPersisting(PersistState, RenderMode.InteractiveAuto);
  15. TryRestoreState();
  16. }
  17. public Guid Guid => _state.TheState;
  18. private void TryRestoreState()
  19. {
  20. if (_componentApplicationState.TryTakeFromJson<ServiceState>("Service", out var state))
  21. {
  22. _state = state;
  23. }
  24. else
  25. {
  26. _state = new ServiceState { TheState = Guid.NewGuid() };
  27. }
  28. }
  29. public void NewState() => _state = new ServiceState { TheState = Guid.NewGuid() };
  30. private Task PersistState()
  31. {
  32. _componentApplicationState.PersistAsJson("Service", _state);
  33. return Task.CompletedTask;
  34. }
  35. public void Dispose() => _persistingSubscription.Dispose();
  36. private class ServiceState
  37. {
  38. public Guid TheState { get; set; }
  39. }
  40. }