❔ BlazorWASM Multi-Tenant Application - Struggle with changing DbContext while Runtime
Hey,
I have created a Blazor WebAssembly (WASM) application, and I would like to select the DatabaseConnection in the user interface, for example, using a Select/Dropdown, and accordingly update the context for this session/user for further queries. However, I am currently facing the issue that the context is not getting updated, and (I suspect) the subsequent functions are called with the initial DbContext of the application during their initialization.
I would appreciate it if someone could help me with this. (I am relatively new to C#/.NET, advice on code is also welcome.)
In the attachments you see the most important parts of the code (I hope). If you need anything else, just ask and I'll provide you with more information.
Attached Files:
Service with function to change context
Service Implementation / Registration
Example use of my dbcontext in my repo for db calls
Thanks and I hope someone is willing to help! :)
I'd love to learn from you.
Greatings Exi
5 Replies
I believe your issue stems from how you use AddDbContext, take a look at https://code-maze.com/efcore-dynamically-switching-dbcontext-at-runtime/#single-dbcontext
I know this isn't your question, but it's a really bad idea to put your database connection into a client-side application. Anyone who uses it will have access to the connection string.
The issue you're running into is related to the lifetime of Blazor WASM services, which scoped is effectively singleton, so you're using the same service for the lifetime of the application.
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection?view=aspnetcore-7.0#service-lifetime
@Zaneris I'm only passing the Database Name and holding the ConnectionString on ServerSide
And thanks, I'll check your links guys!
If you have any other questions #web is a great place to chat about this stuff too.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.