locked
Initialize Singleton variable in Startup and use it in whole app RRS feed

  • Question

  • User-1629310966 posted

    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 in each page in which I want to use the data

    @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?

    Monday, April 5, 2021 8:10 PM

Answers

  • User475983607 posted

    Below is an Blazor WASM example.

    Service

        public interface ISingletonServiceDemo
        {
            Dictionary<string, string> currentValues { get; set; }
        }
    
        public class SingletonServiceDemo : ISingletonServiceDemo
        {
            private readonly ILogger<SingletonServiceDemo> _logger;
            private Dictionary<string, string> _currentValues;
            public SingletonServiceDemo(ILogger<SingletonServiceDemo> logger)
            {
                _logger = logger;
                _currentValues = new Dictionary<string, string>();
            }
    
            public Dictionary<string, string> currentValues
            {
                get => _currentValues;
                set
                {
                    _currentValues = value;
                    _logger.LogInformation("The entire dictionary was set");
                }
            }
        }

    Register

    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");
    
            builder.Logging.SetMinimumLevel(LogLevel.Debug);
    
            builder.Services.AddScoped(sp => new HttpClient
            {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });
    
            builder.Services.AddSingleton<ISingletonServiceDemo, SingletonServiceDemo>();
            var host = builder.Build();
    
            ISingletonServiceDemo service = host.Services.GetRequiredService<ISingletonServiceDemo>();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("Hello", "World");
            service.currentValues = dic;
    
            await host.RunAsync();
        }
    }
    

    Implementation

    @page "/"
    @inject BlazorWasmDemo.Services.ISingletonServiceDemo service
    
    
    Welcome to your new app.
    
    <SurveyPrompt Title="How is Blazor working for you?" />
    
    <div>
        @service.currentValues["Hello"]
    </div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 5, 2021 10:01 PM