I am having issue with the code, I have my page layout as below.
I am communicating to database to get data for Main Content. It is List<SomeClass>
that I am getting from database. Now I want same List<SomeClass>
to be available for RightContent. Both components are custom and have different layout but can share same List rather than making same call twice. (Sequence is MainContent Initialized() method gets called first)
I created a service class AppDataService with below property. Also added to IServiceCollection services
in startup.
public List<SomeClass> sharedListOfSomeClass = new List<SomeClass>();
In MainContent I am injecting AppDataService and assigning sharedListOfSomeClass with database values. Now if I am injecting AppDataService in Right Content and and trying to access sharedListOfSomeClass I am getting it as null.
I know I am missing binding here because both the components are different in terms of html and can't bind it to any html tags.
Could any one please help me out to achieve this. I want to make single call to database for both the components.
If you want to have some global state of the app and share it between different components, the most reasonable way to do it is to create a State
class that will contain the global state data
public class State
{
public List<SomeClass> SomeClassObjectsCollection { get; set; } = new List<SomeClass>();
}
In your Startup
(or Program
if you use Blazor wasm) you should add a State
object as a singleton
services.AddSingleton<State>()
and on every page, where you need an access to state (or even in _Imports
if you want to access it often) add
@inject State State
After that on any page you can refer to State.SomeClassObjectsCollection
and get the same data.
The key point is adding a state as a singleton. If you will add is as transient or even scoped, the dependency container will create new instances of State
.
One option is to pass the list to the components as parameter. Define a parameter in the component's code.
[Parameter] public List<SomeClass> sharedListOfSomeClass { get; set; }
In the parent pass the set the parameter:
<MyCustomComponent sharedListOfSomeClass="@MyVariableHoldingTheListValues" />
Other way I can think of is to make a static list and reference the static list in the components.
The scenario of the injection gives you null because the service could be registered as transient or scoped servervice. Not as singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With