0
votes

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

1
This might be a bit out of scope but what does Database do? 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
Thanks @Joelius, it does manage access to a database - I've not used Entity before but I'll definitely take a look! Our data uses stored procedures for retrieving / updating instead of direct table updates / selects so went for something simple to start with rather than having to learn a framework - Nick
Then you might want to look at dapper. It's also an ORM but you write the queries differently and it's a lot simpler if you have queries in SQL. I can imagine that dapper fits your use case better than EF. - Joelius

1 Answers

0
votes

Just create a constructor for your class:

public AppData()
{
    // perform any initializations here
    Database = new Database();
}