Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor base component action on creation

$
0
0

In Blazor WASM I have a service that has event property. I want to subscribe to this property immediately after the service is injected into component that is the used as a parent component(base class) for other child components.

Example:

public interface ISubService{    event Action<bool> OnLoad;}public partial class ParentComponent : ComponentBase{}

There are several ways how to do it but none of them do what I want (except the hackish workaround at the end)

My options are:

  1. Inject the service through [Inject] or @inject and then use OnInitialized or OnParameterSet. Theoretically I can subscribe to the event in one of those methods but the main problem I have with this is that when a child component uses OnInitialized or OnParameterSet we have to remember to call base.OnInitialized or base.OnParameterSet (Error prone + more code)

  2. The second option was to inject the service through [Inject] or @inject and then calling default constructor. This doesnt work because the constructor is called before those injected services are filled, so I cant access the event

  3. Injecting it through Constructor (.NET9 DI) but this would require us to fill the base constructor everytime it is used inside the child component.

So my main requirement is that the registration logic is only inside the parent and is not propagated in any way into child components.


I was able to achieve this but it feels like hack-ish solution. I did this:

public partial class ParentComponent : ComponentBase{        private ISubService? _subServiceHidden { get; set; }        [Inject] private ISubService _subService        {            get => _subServiceHidden!;            set            {                _subServiceHidden = value;                _subServiceHidden.OnLoad += HandleLoadingAction;            }        }    public void HandleLoadingAction(bool isLoading)    {        // Do something    }}

This way the event is registered immediately after the service is filled and I dont have to adjust child components in any way.


So my questions are:

  • Is it possible to do this in some "normal" way ? Or is this the current blazor limitation.
  • Did you need anything like this in your usecases ?

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>