Finbuckle.MultiTenant icon indicating copy to clipboard operation
Finbuckle.MultiTenant copied to clipboard

EF Core Add-Migrations problem when using AddDbContextFactory

Open richardbartley opened this issue 2 years ago • 2 comments

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?

richardbartley avatar Sep 08 '22 16:09 richardbartley

@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?

AndrewTriesToCode avatar Sep 17 '22 02:09 AndrewTriesToCode

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?

richardbartley avatar Sep 20 '22 08:09 richardbartley

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.

stale[bot] avatar Nov 02 '22 06:11 stale[bot]

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' 

enkodellc avatar Jun 13 '23 11:06 enkodellc

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.

AndrewTriesToCode avatar Jun 15 '23 00:06 AndrewTriesToCode