We've been facing an issue in our Blazor Server App
- User Logs in.
- When user is Authenticated is shown a companies list.
- User can choose between one of the companies in the list.
- In this moment we need to save the CompanyDBName and CompanyUi of the choosen company (The only place we found to store this was ProtectedSessionStorage [Scoped Service], because it's a place with a life cicle of the session, beggining in the user login and ending in user logout).
- We have MainService (MUST be Singleton Service, because it contains other application relevant data) with a DbConnectionString property that stores the connection string without any Initial Catalog and a method GetCompanyConnectionString() that adds CompanyDbName to DbConnectionString and returns CompanyDbConnetionString.
- CompanyDbConnection string is used in all Factories that works with DataBase.
The Issue:
- We can´t get the CompanyDbName inside of the GetCompanyConnectionString() method because the ProtectedSessionStorage is a Scoped Service, and MainService is a Singleton Service.
public class MainService{ private readonly ProtectedSessionStorage _protectedSessionStorage; public string DbConnectionString{ get; set; } = "Data Source=localhost\SQLEXPRESS;Initial Catalog=;Integrated Security=True"; public SessionDataService(ProtectedSessionStorage protectedSessionStorage) { // ***The Error Happens Here *** - in the Injection of ProtectedSessionStorage _protectedSessionStorage = protectedSessionStorage; } async Task<string> GetCompanyConnectionString() { // Get CompanyDbName from ProtectedSessionStorage var companyDbName = await _protectedSessionStorage.GetAsync<string>("UserDb"); // Add to CompanyDbName to DbConnectionString (that is common to all sessions) SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DbConnectionString); builder.InitialCatalog = companyDbName; // returns ConnectionString that we use by A session in the DataBaseFactory calls return builder.ToString(); }}builder.Services.AddSingleton<MainService>();