VSO
VSO

Reputation: 31

Initialize Singleton variable in Startup and use it in wole app

I want to store data in an object and I want to use this in the whole app. I created an Object and register as Singleton in Program.cs

Object:

 private Dictionary<string, string> _currentValues;

 public Dictionary<string, string> currentValues
 {
      get => _currentValues;
      set
      {
           _currentValues = value;
           StateHasChanged();
      }
}

Singleton Registration:

 services.AddSingleton<LocalizeData>();

In program.cs after registration I added initial data.

var _localizeData = host.Services.GetRequiredService<LocalizeData>();
_localizeData.currentValues = locaData;

Now I want to use these data in the whole app. I injected it main Page.

@LocalizeData localizeData

If I use now localizeData.currentValues the object is null.

What is missing. How can I initialize an object in Starttup and how can I use the data in whole app?

Upvotes: 2

Views: 1104

Answers (2)

VSO
VSO

Reputation: 31

The Problem was I used

await builder.Build().RunAsync();

instead of

await host.RunAsync();

This was the reason why I created a second instance and I could not access my initialize data.

See documentation: https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection?view=aspnetcore-5.0&pivots=webassembly

Upvotes: 1

Bennyboy1973
Bennyboy1973

Reputation: 4208

You're almost there. :D

To use services in your component, you need to use the inject keyword:

@inject LocalizeData localizeData

Upvotes: 2

Related Questions