Hello, I am trying to set up a structure as in the picture below using the codes you shared.
![enter image description here](https://camo.githubusercontent.com/8d1018f093716d8902d32f3f4ea15328547d2af1905fe879f3b475d8069ca4cc/68747470733a2f2f692e6962622e636f2f5333345a3033462f6170702e706e67)
The system administrator of this application is "Root User", a user with the ability to add other users to the system.
Gold, silver, bronze .. etc. will have an unlimited user base. Each will have their own database. Let's not get hung up on the naming. These will be in the form of individual customers, not as a group.
All users will log into the application from the same place. If the user is a system administrator, he will only see the area related to users. This is about frontend. If it is in normal user status, it will read the connection string from the "Shared DB" and connect to the relevant database.
I want to save Tenant definitions in "Shared DB" database. Appsettings.json will only have "Shared DB" information.
For example, when "Gold User" logs in, it will read its own connection string from "Shared DB" and continue its operations in "Gold DB". Also, it will not close the other connection so that it can read other data from "Shared DB".
I am trying to add "DB Context" in a multiple way. However, only the 2nd "DB Context" I added works in the controller. It crushes the first.
Can you help me with this part?
For now I'm pulling the Tenant definitions from the appsettings.json file. I am using .Net Core 6.0.
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"TenantSettings": {
"Defaults": {
"DBProvider": "mssql",
"ConnectionString": "Server=192.168.0.78,1435;Database=tenant_SharedDB;User Id=sa;Password=***;"
},
"Tenants": [
{
"Name": "bronze",
"TenantId": "bronze",
"ConnectionString": "Server=192.168.0.78,1435;Database=tenant_BronzeTenantDB;User Id=sa;Password=***;"
},
{
"Name": "silver",
"TenantId": "silver",
"ConnectionString": "Server=192.168.0.78,1435;Database=tenant_SilverTenantDB;User Id=sa;Password=***;"
},
{
"Name": "gold",
"TenantId": "gold",
"ConnectionString": "Server=192.168.0.78,1435;Database=tenant_GoldTenantDB;User Id=sa;Password=***;"
}
]
}
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHttpContextAccessor();
builder.Services.Configure<TenantSettings>(builder.Configuration.GetSection("TenantSettings"));
builder.Services.AddInfrastructureService();
await builder.Services.AddPersistenceService();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/UserControllers/swagger.json", "MultiTenantWebApi - User Tables");
c.SwaggerEndpoint("/swagger/ProductControllers/swagger.json", "MultiTenantWebApi - Product Tables");
});
}
//app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
ServiceRegistration.cs
public static class ServiceRegistration
{
public static void AddInfrastructureService(this IServiceCollection collection)
{
collection.AddTransient<ITenantService, TenantService>();
}
public static async Task AddPersistenceService(this IServiceCollection collection)
{
collection.AddScoped<IUserService, UserService>();
collection.AddScoped<IProductService, ProductService>();
using var provider = collection.BuildServiceProvider();
var configuration = provider.GetRequiredService<IConfiguration>();
var tenantSettings = configuration.GetSection("TenantSettings").Get<TenantSettings>();
var defaultConnectionString = tenantSettings.Defaults?.ConnectionString;
var defaultDbProvider = tenantSettings.Defaults?.DbProvider;
if (defaultDbProvider.ToLower() == "mssql")
{
collection.AddDbContext<SharedDbContext>(option => option.UseSqlServer(e => e.MigrationsAssembly(typeof(SharedDbContext).Assembly.FullName)));
}
using IServiceScope scope = collection.BuildServiceProvider().CreateScope();
// SharedDb Migration
var dbContext = scope.ServiceProvider.GetRequiredService<SharedDbContext>();
dbContext.Database.SetConnectionString(defaultConnectionString);
if (dbContext.Database.GetMigrations().Count() > 0)
await dbContext.Database.MigrateAsync();
if (defaultDbProvider.ToLower() == "mssql")
{
collection.AddDbContext<TenantDbContext>(option => option.UseSqlServer(e => e.MigrationsAssembly(typeof(TenantDbContext).Assembly.FullName)));
}
using IServiceScope scope2 = collection.BuildServiceProvider().CreateScope();
foreach (var tenant in tenantSettings.Tenants)
{
string connectionString = tenant.ConnectionString switch
{
null => defaultConnectionString,
not null => tenant.ConnectionString
};
var dbContext2 = scope2.ServiceProvider.GetRequiredService<TenantDbContext>();
dbContext2.Database.SetConnectionString(connectionString);
if (dbContext2.Database.GetMigrations().Count() > 0)
await dbContext2.Database.MigrateAsync();
}
}
}
With these codes, migrations are working correctly. I have bound the User table to the SharedDbContext. I also bound the Product table to TenantDbContext. The tables are created in the corresponding databases.
Product listing and adding products work correctly in the controller. But user listing, adding user is not working. I am getting an error like this:
![enter image description here](https://camo.githubusercontent.com/f1cdc05fb28302ee4fbc84a6a63a73288c9f5481f86980b6709f48f22c01b16f/68747470733a2f2f692e6962622e636f2f624e6d466477622f4769746875622d69737375652e706e67)
I just need help with controller. Because I couldn't find enough resources for .net core. I don't have enough knowledge. What do I need to do for the controller to work properly?
I wish you good work.