Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to load initial data on Blazor WASM start up

I am building a Blazor app and need to load some initial data when the app starts so that I can put the data into a CascadingPerameter to be used by other components.

I am wondering where the best place to call a service to read this data?

like image 477
Darryl Wagoner WA1GON Avatar asked Oct 14 '25 08:10

Darryl Wagoner WA1GON


2 Answers

In general you should use Services for data. A service is simply an instance of a class accessed through Dependency Injection. Any UI component can access the same instance of that class. The type of service depends on the scope of the data. If it's application wide and fixed during the SPA session, create a scoped or singleton service (depending on whether you're running WASM or Server) and share it though Dependency Injection. If it's "page" scoped, use a Transient Service.

Think UI - Components, Data - Services.

The MS documentation on Services and DI is here

like image 189
MrC aka Shaun Curtis Avatar answered Oct 18 '25 01:10

MrC aka Shaun Curtis


I'd suggest you to inject your service into the MainLayout component, and read the data in the OnInitialized(Async) methods. But if the service can read the data in that phase of the initialization of your app, why can't you inject the service into the components that need it, instead of cascading the data ?

like image 30
enet Avatar answered Oct 18 '25 00:10

enet