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>
Member
1 Points
1 Post
Initialize Singleton variable in Startup and use it in whole app
Apr 05, 2021 08:10 PM|vetsoftone|LINK
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:
Singleton Registration:
In program.cs after registration I added initial data.
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
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?All-Star
53661 Points
24018 Posts
Re: Initialize Singleton variable in Startup and use it in whole app
Apr 05, 2021 10:01 PM|mgebhard|LINK
Below is an Blazor WASM example.
Service
Register
Implementation