I'm new to Blazor and have been looking at a way to share an instance of a class between components in my server side Blazor App.
Most of the searching I've done so far recommends doing this through a singleton service.
I have a Database class that almost all the components will use.
I'd like to initialise it when the webapp starts up and share this new instance between all the components.
I've created an AppData class:
public class AppData
{
public Database Database { get; set; }
}
I've added the class as a singleton in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<Data.AppData>();
}
At this point, is there a way to set the Database property on startup e.g AppData.Database = new Database(...) so that it's already set when the other components come to use it?
As a follow on question I've also added a property to the AppData class to serve as a kind of global variable so I can pass data from one page to another
public class AppData
{
public WorkflowTask Task { get; set; }
public Database Database { get; set; }
}
I don't want AppData to become a dumping ground of global variables just so I can pass objects/primitives between components - have I just got the wrong end of the stick? Is there a standard way of doing this?
Many Thanks
Nick
Databasedo? If it's a class to manage access to an actual database, you should look into an ORM like Entity Framework (core). It will do all the heavy lifting for you and synergize very well with the asp.net (core) ecosystem including dependency injection. - Joelius