Finbuckle.MultiTenant
Finbuckle.MultiTenant copied to clipboard
Manual Tenant Switching Issue
Discussed in https://github.com/Finbuckle/Finbuckle.MultiTenant/discussions/590
Originally posted by Rockstar1989 September 21, 2022 Hi there;
I hope that you are doing well.
I have an enquiry with regards to switching a tenant at runtime, specifically, cycling through tenant IDs/identifiers to resolve their respective Database Contexts and carry out some sort of persistence.
We are currently making use of the host strategy for tenant resolution which of course works just fine, but we now have a use case where, given a list of tenant IDs, we want to persist some data to each tenant DB. This would be taking place in one of our API services - this can be thought of an "admin-level" task. Therefore, we would like to change the resolved tenant at runtime for each provided tenantId and use its resolved Database Context for persistence.
According to your documentation, the following line seems to provide what we are looking for, however, the Database Context after this call is not resolved.
_httpContextAccessor.HttpContext?.TrySetTenantInfo(tenantInfo, true);
Is the Database Context not being resolved for a newly set tenant expected behavior?
If so, what is value provided by the above line? What use case is the above satisfying/achieving?
If not, may I please ask for some assistance on what we may be doing incorrectly, and for any information that we have missed and should be aware of when tackling this problem/use case.
I look forward to hearing from you, thank you!
hi @Rockstar1989
Would an approach like this work for you? this is from the Identity sample that loops through the tenants to run migrations but could also work for general dbcontext needs:
// Apply migrations if needed
var store = app.Services.GetRequiredService<IMultiTenantStore<TenantInfo>>();
foreach(var tenant in await store.GetAllAsync())
{
using var db = new ApplicationDbContext(tenant);
await db.Database.MigrateAsync();
}
This is nice because it takes DI out of the picture but it might be too simplistic for your use case.
It is possible to do this using DI by overwriting the tenant. It's clunky and I'm trying to create a nice extension method to make it easier to do.
Hi @AndrewTriesToCode
Thank you for this solution. This seems to have done the trick for me.
Much appreciated
Great, I'm going to close the issue but don't hesitate to reopen if needed.