Hi,
I want to create a multi-tenant app, and I want to register an ITenantService with the container, then, I want the DbContext to be created with a connection-string according to the current tenant.
What's the recommended way to do that?
I thought about inheriting from DbContextOptions, but I found no way to address the connection-string.
⚠Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
You can inject ITenantService into your DbContext, and then in you can dynamically set the connection string in OnConfiguring.
@TrieBr thanks.
Question is when to call Database.Migrate.
Good question, I can't think of any way that is very elegant.
You could loop through each tenant, create a ServiceProvider Scope, have a way to manually override the value that ITenantService returns, then instantiate your DbContext from the scope, and it would connect to your "faked" tenantId
What I ended up doing is, in the controller, upon the creation of the tenant, I call an explicit DbContext with a dummy ITenantProvider, that provides the newly created tenant, and migrate it.
Thanks for your comments!
Most helpful comment
You can inject ITenantService into your DbContext, and then in you can dynamically set the connection string in
OnConfiguring.