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.33k stars 266 forks source link

A relational store has been configured without specifying either the DbConnection or connection string to use. #769

Open DesertMountSolution opened 1 year ago

DesertMountSolution commented 1 year ago

Can not connect to database.

Register

services.AddMultiTenant<TenantInfo>()
    .WithEFCoreStore<MultiTenantStoreDbContext, TenantInfo>()
    .WithRouteStrategy()
    .WithRedirectStrategy("/notenant/index");

EfContext

public class MultiTenantStoreDbContext : EFCoreStoreDbContext<TenantInfo>
{
    private readonly IConfiguration _configuration;

    public MultiTenantStoreDbContext(DbContextOptions<MultiTenantStoreDbContext> options,
        IConfiguration configuration) : base(options)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionString = _configuration.GetConnectionString("MultiTenant");

        var serverVersion = ServerVersion.AutoDetect(connectionString);

        optionsBuilder.UseMySql(serverVersion);

        base.OnConfiguring(optionsBuilder);
    }
}

Try to resolve tenant store

using var scope = app.ApplicationServices.CreateScope();
var store = scope.ServiceProvider.GetRequiredService<IMultiTenantStore<TenantInfo>>();            

var tenants = await store.GetAllAsync();

GetAllAsync throws an exception with "A relational store has been configured without specifying either the DbConnection or connection string to use."

DesertMountSolution commented 1 year ago

I need to set connection string in constructor.


public MultiTenantStoreDbContext(DbContextOptions<MultiTenantStoreDbContext> options,
    IConfiguration configuration) : base(options)
{
    _configuration = configuration;

    var connectionString = _configuration.GetConnectionString("MultiTenant");

    Database.SetConnectionString(connectionString);
}
AndrewTriesToCode commented 1 year ago

hi @DesertMountSolution

I'm not familiar with using server version and autodetect like you have here:

var connectionString = _configuration.GetConnectionString("MultiTenant");
var serverVersion = ServerVersion.AutoDetect(connectionString); 
optionsBuilder.UseMySql(serverVersion);

Does UseMySql not just accept the connection string as normal?

There's nothing special about EFCoreStoreDbContext<TenantInfo> in how it connects to a database. The usual approach of assigning the provider and connection string wither in the service setup or in OnConfiguring should work just like any other db context.