CustomFluentValidator.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using Microsoft.AspNetCore.Components;
  2. using Microsoft.AspNetCore.Components.Forms;
  3. namespace BlazorEditForms;
  4. public class CustomFluentValidator : ComponentBase, IDisposable
  5. {
  6. private IDisposable? _subscriptions;
  7. private EditContext? _originalEditContext;
  8. [CascadingParameter] EditContext? CurrentEditContext { get; set; }
  9. [Inject] private IServiceProvider ServiceProvider { get; set; } = default!;
  10. protected override void OnInitialized()
  11. {
  12. if (CurrentEditContext == null)
  13. {
  14. throw new InvalidOperationException($"{nameof(DataAnnotationsValidator)} requires a cascading " +
  15. $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(DataAnnotationsValidator)} " +
  16. $"inside an EditForm.");
  17. }
  18. _subscriptions = new CustomFluentValidationManager(CurrentEditContext, ServiceProvider);
  19. _originalEditContext = CurrentEditContext;
  20. }
  21. protected override void OnParametersSet()
  22. {
  23. if (CurrentEditContext != _originalEditContext)
  24. {
  25. // While we could support this, there's no known use case presently. Since InputBase doesn't support it,
  26. // it's more understandable to have the same restriction.
  27. throw new InvalidOperationException($"{GetType()} does not support changing the " +
  28. $"{nameof(EditContext)} dynamically.");
  29. }
  30. }
  31. public void Dispose()
  32. {
  33. _subscriptions?.Dispose();
  34. _subscriptions = null;
  35. }
  36. }