Entityframework.docs: Injectable connection string?

Created on 27 May 2019  Â·  4Comments  Â·  Source: dotnet/EntityFramework.Docs

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.


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Most helpful comment

You can inject ITenantService into your DbContext, and then in you can dynamically set the connection string in OnConfiguring.

All 4 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SychevIgor picture SychevIgor  Â·  4Comments

jpeckham picture jpeckham  Â·  3Comments

ajcvickers picture ajcvickers  Â·  4Comments

divega picture divega  Â·  4Comments

speciesunknown picture speciesunknown  Â·  3Comments