Click here to Skip to main content
16,022,333 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a BlazorApp and declared and initialized an instance in serverside Program.cs like:

Program.cs:
namespace BlazorApp
{
    public class Program
    {
        public static DataAccessService dsService = new DataAccessService();
        public static void Main(string[] args)
        {
            ....
        }
    }
    public static class DataAccessService
    {
        public string? str1 = null;
        public string? str2 = null;

        public void InitData()
        {
            str1 = "hu1";
            str2 = "hu2";
        }
    }
}


in client page e.g. Counter.razor:
i have to access the object and its member
dsService.str1 = "something 1"
dsService.str2 = "something 2" 


How does this work?

thanks!

What I have tried:

i'm new in Blazor Server app programming and need some strategies :)
Posted

1 solution

In your code, daService is a static field within the Program class. To access it from another class, you would need to prefix the field name with the class name:
C#
Program.daService.str1
However, this is almost certainly the wrong thing to do.

Since you have declared the instance as a static field, that single instance will be shared across the entire process. Every single request that comes in will be accessing the same instance, and each request will be accessing it from a different thread. Not only will you have thread-safety issues to worry about, but if you're using the class to store anything related to a request, then you will end up with data "leaking" between requests.

It would almost certainly be better to use dependency injection:
ASP.NET Core Blazor dependency injection | Microsoft Learn[^]

If the data in your class relates to a single request, register it as a "scoped" service.

If it's genuinely a "singleton" service, then it should ideally be immutable.
 
Share this answer
 
Comments
-K=O=N=A- 4-Sep-24 3:33am    
thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900