零框架多租户设计方案

This commit is contained in:
administrator committed 2024-04-28 16:00:15 +08:00
1 parent b7caaa2d0c
commit b4a704526d
42 files changed
+1002 -1

No files matched your search

@@ -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"
}
}