Static class Vs injection in Blazor server

Viewed 2998

I am a WPF developer. I am part of a team that has developed an ERP application. I want to convert the application into Blazor Server for the web. I am new to web technology and Blazor.

We have a static class that has nearly 50 properties (only properties, no methods) to store certain data at the application level. We set these property values when the user logs in. After that, we use these values wherever they are required.

Now my question is, how can I use this class in Blazor? I have searched the web and found two ways.

  1. Add a singleton service. Inject it in wherever required and use its values.
  2. Use the static class directly wherever required, without service injection.

Which is the best approach in my case, and why?

1 Answers

Both approaches could be "syntactically" correct but the dependency injection will give you the best flexibility. Since the transition to .NET Core, DI is integrated in the framework, so it's quite straightforward to implement it (although hard to dominate it on the beggining).

Anyway, reading your question, it seems that you pretend to store some user related data for later use. If that's the case then a singleton won't be the best choice here, since you're now on a multiuser environment and all users would be accessing the same instance everytime.

You should create a factory that creates that class for each user, and then register it on DI as scoped, since that kind of objects last all the session of the user.

Here you will find a useful doc from Microsoft about what you're trying to achieve, including patterns and practices:

Configuration Dependency Injection

Best regards

Related