零框架多租户设计方案
This commit is contained in:
parent
b7caaa2d0c
commit
b4a704526d
@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.DatabaseIsolationService.Entities;
|
||||
using MultiTenancySample.DatabaseIsolationService.EntityFrameworks;
|
||||
|
||||
namespace MultiTenancySample.DatabaseIsolationService.Controllers
|
||||
{
|
||||
[Route("api/{tenant}/[controller]")]
|
||||
[ApiController]
|
||||
public class ProductsController(IDbContextFactory<DatabaseIsolationServiceDbContext> dbContextFactory) : ControllerBase
|
||||
{
|
||||
private readonly DatabaseIsolationServiceDbContext _dbContext = dbContextFactory.CreateDbContext();
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetProducts(string? keyword)
|
||||
{
|
||||
IQueryable<Product> products = _dbContext.Set<Product>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
products = products.Where(p => p.Name.Contains(keyword));
|
||||
}
|
||||
|
||||
return Ok(products);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
namespace MultiTenancySample.DatabaseIsolationService.Entities
|
||||
{
|
||||
public class Product
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.DatabaseIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.DatabaseIsolationService.EntityFrameworks
|
||||
{
|
||||
public class DataSeeding(IDbContextFactory<DatabaseIsolationServiceDbContext> dbContext, ICurrentTenant currentTenant)
|
||||
{
|
||||
public async Task SeedDataAsync()
|
||||
{
|
||||
currentTenant.SetTenant("Tenant1");
|
||||
|
||||
DatabaseIsolationServiceDbContext dbContext1 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext1.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext1.AddRangeAsync(new List<Product> {
|
||||
new() { Id = Guid.NewGuid(), Name = "Product1"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product3"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product5"}
|
||||
});
|
||||
|
||||
await dbContext1.SaveChangesAsync();
|
||||
}
|
||||
|
||||
currentTenant.SetTenant("Tenant2");
|
||||
|
||||
DatabaseIsolationServiceDbContext dbContext2 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext2.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext2.AddRangeAsync(new List<Product>
|
||||
{
|
||||
new() { Id = Guid.NewGuid(), Name = "Product2"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product4"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product6"}
|
||||
});
|
||||
|
||||
await dbContext2.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.DatabaseIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
|
||||
namespace MultiTenancySample.DatabaseIsolationService.EntityFrameworks
|
||||
{
|
||||
public class DatabaseIsolationServiceDbContext(DbContextOptions<DatabaseIsolationServiceDbContext> options, ICurrentTenant currentTenant, IConfiguration configuration) : DbContext(options)
|
||||
{
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Product>().Property(p => p.Name).HasMaxLength(32);
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
if (currentTenant.TenantId != null)
|
||||
{
|
||||
string? connectionString = configuration.GetConnectionString(currentTenant.TenantId);
|
||||
|
||||
optionsBuilder.UseNpgsql(connectionString);
|
||||
}
|
||||
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MultiTenancySample.ServiceDefaults\MultiTenancySample.ServiceDefaults.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,42 @@
|
||||
using MultiTenancySample.DatabaseIsolationService.EntityFrameworks;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddDbContextFactory<DatabaseIsolationServiceDbContext>(lifetime: ServiceLifetime.Scoped);
|
||||
|
||||
builder.Services.AddScoped<DataSeeding>();
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
builder.Services.AddMultiTenancy();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseMultiTenancy();
|
||||
|
||||
var serviceProvider = app.Services.CreateScope().ServiceProvider;
|
||||
var dataSeeding = serviceProvider.GetRequiredService<DataSeeding>();
|
||||
await dataSeeding.SeedDataAsync();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:62504",
|
||||
"sslPort": 44361
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5220",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7102;http://localhost:5220",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ConnectionStrings": {
|
||||
"Tenant1": "Host=localhost;Port=5432;Database=DatabaseIsolationService1;Username=postgres;Password=postgres",
|
||||
"Tenant2": "Host=localhost;Port=5432;Database=DatabaseIsolationService2;Username=postgres;Password=postgres"
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.FieldIsolationService.Entities;
|
||||
using MultiTenancySample.FieldIsolationService.EntityFrameworks;
|
||||
|
||||
namespace MultiTenancySample.FieldIsolationService.Controllers
|
||||
{
|
||||
[Route("api/{tenant}/[controller]")]
|
||||
[ApiController]
|
||||
public class ProductsController(IDbContextFactory<FieldIsolationServiceDbContext> dbContextFactory) : ControllerBase
|
||||
{
|
||||
private readonly FieldIsolationServiceDbContext _dbContext = dbContextFactory.CreateDbContext();
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetProducts(string? keyword)
|
||||
{
|
||||
IQueryable<Product> products = _dbContext.Set<Product>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
products = products.Where(p => p.Name.Contains(keyword));
|
||||
}
|
||||
|
||||
return Ok(products);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
namespace MultiTenancySample.FieldIsolationService.Entities
|
||||
{
|
||||
public interface IMultiTenant
|
||||
{
|
||||
string? TenantId { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace MultiTenancySample.FieldIsolationService.Entities
|
||||
{
|
||||
public class Product : IMultiTenant
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string? TenantId { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.FieldIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
|
||||
{
|
||||
public class DataSeeding(IDbContextFactory<FieldIsolationServiceDbContext> dbContext, ICurrentTenant currentTenant)
|
||||
{
|
||||
public async Task SeedDataAsync()
|
||||
{
|
||||
currentTenant.SetTenant("Tenant1");
|
||||
|
||||
FieldIsolationServiceDbContext dbContext1 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext1.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext1.AddRangeAsync(new List<Product> {
|
||||
new() { Id = Guid.NewGuid(), Name = "Product1"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product3"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product5"}
|
||||
});
|
||||
|
||||
await dbContext1.SaveChangesAsync();
|
||||
}
|
||||
|
||||
currentTenant.SetTenant("Tenant2");
|
||||
|
||||
FieldIsolationServiceDbContext dbContext2 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext2.Set<Product>().IgnoreQueryFilters().CountAsync() < 6)
|
||||
{
|
||||
await dbContext2.AddRangeAsync(new List<Product>
|
||||
{
|
||||
new() { Id = Guid.NewGuid(), Name = "Product2"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product4"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product6"}
|
||||
});
|
||||
|
||||
await dbContext2.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
using Microsoft.EntityFrameworkCore.Query;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
|
||||
{
|
||||
public static class EntityTypeBuilderQueryFilterExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Support multiple HasQueryFilter calls on same entity type
|
||||
/// https://github.com/dotnet/efcore/issues/10275
|
||||
/// </summary>
|
||||
public static void AddQueryFilter<T>(this EntityTypeBuilder entityTypeBuilder, Expression<Func<T, bool>> expression)
|
||||
{
|
||||
ParameterExpression parameterType = Expression.Parameter(entityTypeBuilder.Metadata.ClrType);
|
||||
Expression expressionFilter = ReplacingExpressionVisitor.Replace(expression.Parameters.Single(), parameterType, expression.Body);
|
||||
|
||||
LambdaExpression? currentQueryFilter = entityTypeBuilder.Metadata.GetQueryFilter();
|
||||
if (currentQueryFilter is not null)
|
||||
{
|
||||
Expression currentExpressionFilter = ReplacingExpressionVisitor.Replace(currentQueryFilter.Parameters.Single(), parameterType, currentQueryFilter.Body);
|
||||
expressionFilter = Expression.AndAlso(currentExpressionFilter, expressionFilter);
|
||||
}
|
||||
|
||||
LambdaExpression lambdaExpression = Expression.Lambda(expressionFilter, parameterType);
|
||||
entityTypeBuilder.HasQueryFilter(lambdaExpression);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using MultiTenancySample.FieldIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
|
||||
{
|
||||
public class FieldIsolationServiceDbContext(DbContextOptions<FieldIsolationServiceDbContext> options, ICurrentTenant currentTenant) : DbContext(options)
|
||||
{
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Product>().Property(p => p.Name).HasMaxLength(32);
|
||||
|
||||
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
|
||||
{
|
||||
if (entityType.ClrType.IsAssignableTo(typeof(IMultiTenant)))
|
||||
{
|
||||
modelBuilder.Entity(entityType.ClrType).AddQueryFilter<IMultiTenant>(e => e.TenantId == currentTenant.TenantId);
|
||||
}
|
||||
}
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
optionsBuilder.AddInterceptors(new TenantSaveChangesInterceptor(currentTenant));
|
||||
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using MultiTenancySample.FieldIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
|
||||
{
|
||||
public class TenantSaveChangesInterceptor(ICurrentTenant currentTenant) : SaveChangesInterceptor
|
||||
{
|
||||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
if (eventData.Context is not null)
|
||||
{
|
||||
MultiTenancyTracking(eventData.Context);
|
||||
}
|
||||
|
||||
return base.SavingChanges(eventData, result);
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (eventData.Context is not null)
|
||||
{
|
||||
MultiTenancyTracking(eventData.Context);
|
||||
}
|
||||
|
||||
return base.SavingChangesAsync(eventData, result, cancellationToken);
|
||||
}
|
||||
|
||||
private void MultiTenancyTracking(DbContext dbContext)
|
||||
{
|
||||
IEnumerable<EntityEntry<IMultiTenant>> multiTenancyEntries = dbContext.ChangeTracker.Entries<IMultiTenant>().Where(entry => entry.State == EntityState.Added || entry.State == EntityState.Modified);
|
||||
|
||||
multiTenancyEntries?.ToList().ForEach(entityEntry =>
|
||||
{
|
||||
entityEntry.Entity.TenantId ??= currentTenant.TenantId;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MultiTenancySample.ServiceDefaults\MultiTenancySample.ServiceDefaults.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,46 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.FieldIsolationService.EntityFrameworks;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddDbContextFactory<FieldIsolationServiceDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("Default"));
|
||||
}, lifetime: ServiceLifetime.Scoped);
|
||||
|
||||
builder.Services.AddScoped<DataSeeding>();
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
builder.Services.AddMultiTenancy();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseMultiTenancy();
|
||||
|
||||
var serviceProvider = app.Services.CreateScope().ServiceProvider;
|
||||
var dataSeeding = serviceProvider.GetRequiredService<DataSeeding>();
|
||||
await dataSeeding.SeedDataAsync();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:40935",
|
||||
"sslPort": 44346
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5072",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7237;http://localhost:5072",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ConnectionStrings": {
|
||||
"Default": "Host=localhost;Port=5432;Database=FieldIsolationService;Username=postgres;Password=postgres"
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.SchemaIsolationService.Entities;
|
||||
using MultiTenancySample.SchemaIsolationService.EntityFrameworks;
|
||||
|
||||
namespace MultiTenancySample.SchemaIsolationService.Controllers
|
||||
{
|
||||
[Route("api/{tenant}/[controller]")]
|
||||
[ApiController]
|
||||
public class ProductsController(IDbContextFactory<SchemaIsolationDbContext> dbContextFactory) : ControllerBase
|
||||
{
|
||||
private readonly SchemaIsolationDbContext _dbContext = dbContextFactory.CreateDbContext();
|
||||
|
||||
[HttpGet]
|
||||
public IActionResult GetProducts(string? keyword)
|
||||
{
|
||||
IQueryable<Product> products = _dbContext.Set<Product>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
products = products.Where(p => p.Name.Contains(keyword));
|
||||
}
|
||||
|
||||
return Ok(products);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
namespace MultiTenancySample.SchemaIsolationService.Entities
|
||||
{
|
||||
public class Product
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.SchemaIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.SchemaIsolationService.EntityFrameworks
|
||||
{
|
||||
public class DataSeeding(IDbContextFactory<SchemaIsolationDbContext> dbContext, ICurrentTenant currentTenant)
|
||||
{
|
||||
public async Task SeedDataAsync()
|
||||
{
|
||||
currentTenant.SetTenant("Tenant1");
|
||||
|
||||
SchemaIsolationDbContext dbContext1 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext1.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext1.AddRangeAsync(new List<Product> {
|
||||
new() { Id = Guid.NewGuid(), Name = "Product1"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product3"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product5"}
|
||||
});
|
||||
|
||||
await dbContext1.SaveChangesAsync();
|
||||
}
|
||||
|
||||
currentTenant.SetTenant("Tenant2");
|
||||
|
||||
SchemaIsolationDbContext dbContext2 = dbContext.CreateDbContext();
|
||||
|
||||
await dbContext2.Database.MigrateAsync();
|
||||
|
||||
if (await dbContext2.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext2.AddRangeAsync(new List<Product>
|
||||
{
|
||||
new() { Id = Guid.NewGuid(), Name = "Product2"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product4"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product6"}
|
||||
});
|
||||
|
||||
await dbContext2.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.SchemaIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.SchemaIsolationService.EntityFrameworks
|
||||
{
|
||||
public class SchemaIsolationDbContext(DbContextOptions<SchemaIsolationDbContext> options, ICurrentTenant currentTenant) : DbContext(options)
|
||||
{
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Product>().Property(p => p.Name).HasMaxLength(32);
|
||||
|
||||
// This scenario is not directly supported by EF Core and is not a recommended solution.
|
||||
// https://learn.microsoft.com/en-us/ef/core/miscellaneous/multitenancy
|
||||
|
||||
modelBuilder.HasDefaultSchema(currentTenant.TenantId);
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MultiTenancySample.ServiceDefaults\MultiTenancySample.ServiceDefaults.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Update="appsettings.Development.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</Content>
|
||||
<Content Update="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,46 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.SchemaIsolationService.EntityFrameworks;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
builder.Services.AddDbContextFactory<SchemaIsolationDbContext>(options =>
|
||||
{
|
||||
options.UseNpgsql(builder.Configuration.GetConnectionString("Default"));
|
||||
}, lifetime: ServiceLifetime.Scoped);
|
||||
|
||||
builder.Services.AddScoped<DataSeeding>();
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
builder.Services.AddMultiTenancy();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseMultiTenancy();
|
||||
|
||||
var serviceProvider = app.Services.CreateScope().ServiceProvider;
|
||||
var dataSeeding = serviceProvider.GetRequiredService<DataSeeding>();
|
||||
await dataSeeding.SeedDataAsync();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:40979",
|
||||
"sslPort": 44360
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "http://localhost:5258",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"applicationUrl": "https://localhost:7264;http://localhost:5258",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ConnectionStrings": {
|
||||
"Default": "Host=localhost;Port=5432;Database=SchemaIsolationService;Username=postgres;Password=postgres"
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
namespace MultiTenancySample.ServiceDefaults
|
||||
{
|
||||
public class CurrentTenant : ICurrentTenant
|
||||
{
|
||||
public string? TenantId { get; private set; }
|
||||
|
||||
public IDisposable SetTenant(string? tenantId)
|
||||
{
|
||||
string? parentTenantId = TenantId;
|
||||
|
||||
TenantId = tenantId;
|
||||
|
||||
return new DisposeAction(() =>
|
||||
{
|
||||
TenantId = parentTenantId;
|
||||
});
|
||||
}
|
||||
|
||||
public class DisposeAction(Action action) : IDisposable
|
||||
{
|
||||
void IDisposable.Dispose()
|
||||
{
|
||||
action();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
namespace MultiTenancySample.ServiceDefaults
|
||||
{
|
||||
public interface ICurrentTenant
|
||||
{
|
||||
string? TenantId { get; }
|
||||
|
||||
IDisposable SetTenant(string? tenantId);
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
namespace MultiTenancySample.ServiceDefaults
|
||||
{
|
||||
public interface ITenantIdProvider
|
||||
{
|
||||
Task<string?> GetTenantIdAsync();
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace MultiTenancySample.ServiceDefaults
|
||||
{
|
||||
public static class MultiTenancyExtensions
|
||||
{
|
||||
public static IServiceCollection AddMultiTenancy(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped<ICurrentTenant, CurrentTenant>();
|
||||
services.AddScoped<ITenantIdProvider, TenantIdProvider>();
|
||||
|
||||
return services.AddScoped<TenantMiddleware>();
|
||||
}
|
||||
|
||||
public static IApplicationBuilder UseMultiTenancy(this IApplicationBuilder app)
|
||||
{
|
||||
app.UseMiddleware<TenantMiddleware>();
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -0,0 +1,12 @@
|
||||
{
|
||||
"profiles": {
|
||||
"MultiTenancySample.ServiceDefaults": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"applicationUrl": "https://localhost:61544;http://localhost:61545"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace MultiTenancySample.ServiceDefaults
|
||||
{
|
||||
public class TenantIdProvider(IHttpContextAccessor httpContextAccessor) : ITenantIdProvider
|
||||
{
|
||||
public async Task<string?> GetTenantIdAsync()
|
||||
{
|
||||
HttpContext httpContext = httpContextAccessor.HttpContext ?? new DefaultHttpContext();
|
||||
|
||||
const string tenantKey = "tenant";
|
||||
|
||||
if (httpContext.Request.Headers.TryGetValue(tenantKey, out var headerValues))
|
||||
{
|
||||
return headerValues.First();
|
||||
}
|
||||
|
||||
if (httpContext.Request.Query.TryGetValue(tenantKey, out var queryValues))
|
||||
{
|
||||
return queryValues.First();
|
||||
}
|
||||
|
||||
if (httpContext.Request.Cookies.TryGetValue(tenantKey, out var cookieValue))
|
||||
{
|
||||
return cookieValue;
|
||||
}
|
||||
|
||||
if (httpContext.Request.RouteValues.TryGetValue(tenantKey, out var routeValue))
|
||||
{
|
||||
return routeValue?.ToString();
|
||||
}
|
||||
|
||||
return await Task.FromResult<string?>(null);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace MultiTenancySample.ServiceDefaults
|
||||
{
|
||||
public class TenantMiddleware(ICurrentTenant currentTenant, ITenantIdProvider tenantProvider) : IMiddleware
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
||||
{
|
||||
string? tenantId = await tenantProvider.GetTenantIdAsync();
|
||||
|
||||
using (currentTenant.SetTenant(tenantId))
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
43
samples/MultiTenancySample/MultiTenancySample.sln
Normal file
43
samples/MultiTenancySample/MultiTenancySample.sln
Normal file
@ -0,0 +1,43 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.9.34728.123
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiTenancySample.SchemaIsolationService", "MultiTenancySample.SchemaIsolationService\MultiTenancySample.SchemaIsolationService.csproj", "{57818F02-DC4F-44CD-89A6-75D00AB5640C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiTenancySample.DatabaseIsolationService", "MultiTenancySample.DatabaseIsolationService\MultiTenancySample.DatabaseIsolationService.csproj", "{340A9AE9-C3FA-4555-86AF-395780D2B89B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiTenancySample.FieldIsolationService", "MultiTenancySample.FieldIsolationService\MultiTenancySample.FieldIsolationService.csproj", "{0B3EB138-AE17-4EB0-B282-88777F6D5FCA}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiTenancySample.ServiceDefaults", "MultiTenancySample.ServiceDefaults\MultiTenancySample.ServiceDefaults.csproj", "{CF4169D1-AB89-42FD-B209-FCBA9B6F0816}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{57818F02-DC4F-44CD-89A6-75D00AB5640C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{57818F02-DC4F-44CD-89A6-75D00AB5640C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{57818F02-DC4F-44CD-89A6-75D00AB5640C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{57818F02-DC4F-44CD-89A6-75D00AB5640C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{340A9AE9-C3FA-4555-86AF-395780D2B89B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{340A9AE9-C3FA-4555-86AF-395780D2B89B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{340A9AE9-C3FA-4555-86AF-395780D2B89B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{340A9AE9-C3FA-4555-86AF-395780D2B89B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0B3EB138-AE17-4EB0-B282-88777F6D5FCA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0B3EB138-AE17-4EB0-B282-88777F6D5FCA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0B3EB138-AE17-4EB0-B282-88777F6D5FCA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0B3EB138-AE17-4EB0-B282-88777F6D5FCA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{CF4169D1-AB89-42FD-B209-FCBA9B6F0816}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{CF4169D1-AB89-42FD-B209-FCBA9B6F0816}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CF4169D1-AB89-42FD-B209-FCBA9B6F0816}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CF4169D1-AB89-42FD-B209-FCBA9B6F0816}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {201289BC-2E55-46AF-AD01-B3D4288D9904}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
20
samples/MultiTenancySample/README.md
Normal file
20
samples/MultiTenancySample/README.md
Normal file
@ -0,0 +1,20 @@
|
||||
# 零框架多租户设计方案
|
||||
|
||||
多租户应用程序是一种软件架构设计,允许单个实例的软件服务多个客户,每个客户被称为一个租户,租户之间的数据自动隔离的,租户之间的数据不会相互影响,租户和用户是一对多的关系。
|
||||
|
||||
## 零度框架中实现多租户
|
||||
|
||||
由于每个系统的需求不同,零度框架没有提供多租户的通用解决方案,但我们提供了三种多租户设计的思路,并提供了示例代码,以便于开发者根据自己的需求来实现多租户设计。
|
||||
|
||||
## 基于单表字段隔离租户数据
|
||||
|
||||
单表多租户设计是指在一个表中存储多个租户的数据,通过在表中增加一个 TenantId 字段来区分不同租户的数据,使用全局查询过滤器来过滤租户数据,使用拦截器来保存租户数据。
|
||||
|
||||
|
||||
## 基于多数据库隔离租户数据
|
||||
|
||||
多数据库多租户设计是指为每个租户创建一个独立的数据库,通过数据库连接字符串来区分不同租户的数据,使用拦截器来设置数据库连接字符串。
|
||||
|
||||
## 基于单数据库架构隔离租户数据
|
||||
|
||||
基于 Schema 的多租户设计是指为每个租户创建一个独立的 Schema 名称 ,通过 Schema 来区分不同租户的数据,使用拦截器来设置 Schema 名称。
|
6
samples/MultiTenancySample/global.json
Normal file
6
samples/MultiTenancySample/global.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "8.0.204",
|
||||
"rollForward": "latestFeature"
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
# 示例代码
|
Loading…
Reference in New Issue
Block a user