Initialize Singleton variable in Startup and use it in wole app

Viewed 495

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?

2 Answers

You're almost there. :D

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

@inject LocalizeData localizeData
Related