Finbuckle / Finbuckle.MultiTenant

Finbuckle.MultiTenant is an open-source multitenancy middleware library for .NET. It enables tenant resolution, per-tenant app behavior, and per-tenant data isolation.
https://www.finbuckle.com/multitenant
Apache License 2.0
1.3k stars 266 forks source link

EF Core Add-Migrations problem when using AddDbContextFactory #585

Closed richardbartley closed 1 year ago

richardbartley commented 2 years ago

When adding ApplicationDbContext (based on BaseDbContext : MultiTenantIdentityDbContext), I can do EF migrations as if finds the Tenant.

.AddDbContext<ApplicationDbContext>( m => m.UseDatabase(dbProvider, rootConnectionString))

However, when using the Factory approach,

.AddDbContextFactory<ApplicationDbContext>(
                m => m.UseDatabase(dbProvider, rootConnectionString)

the EF Add-Migrations tooling fails with this error.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.InvalidOperationException: Unable to resolve service for type 'Finbuckle.MultiTenant.ITenantInfo' while attempting to activate 'MyProject.API.Infrastructure.Persistence.Context.ApplicationDbContext'.

What can I do to resolve this while using the AddDbContextFactory?

AndrewTriesToCode commented 2 years ago

@richardbartley I appreciate you bringing this up. I don't have a good answer at the moment and haven't gotten into DbContextFactory much myself -- I realize its important in Blazor and I need to do so.

In this case is it trying to spin up a dbcontext outside of an HttpRequest? Like at startup or in a background service?

richardbartley commented 1 year ago

Yes its a problem in StartUp and when using the Add-Migration tooling. It doesn't know the TenantInfo. Wonder if there is a trick to provide one perhaps at DesignTime?

stale[bot] commented 1 year ago

This issue has been automatically marked for closure because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

enkodellc commented 1 year ago

We are getting a similar error when trying to use an Id


        private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;

        using var appDbContext = _appDbContextFactory.CreateDbContext();
    (Unable to resolve service for type 'Finbuckle.MultiTenant.TenantInfo' while attempting to activate 'BlazorBoilerplate.Storage.ApplicationDbContext'.) ---> System.InvalidOperationException: Unable to resolve service for type 'Finbuckle.MultiTenant.TenantInfo' while attempting to activate 'BlazorBoilerplate.Storage.ApplicationDbContext' 
AndrewTriesToCode commented 1 year ago

One idea is to register a "dummy" interface in DI which uses a lambda to instantiate your dbcontext with a constructor of your choice, i.e. one that isn't dependent on the tenant.