|
| 1 | +using System.Net; |
| 2 | +using DatabasePerTenantExample.Models; |
| 3 | +using JetBrains.Annotations; |
| 4 | +using JsonApiDotNetCore.Errors; |
| 5 | +using JsonApiDotNetCore.Serialization.Objects; |
| 6 | +using Microsoft.EntityFrameworkCore; |
| 7 | + |
| 8 | +namespace DatabasePerTenantExample.Data; |
| 9 | + |
| 10 | +[UsedImplicitly(ImplicitUseTargetFlags.Members)] |
| 11 | +public sealed class AppDbContext : DbContext |
| 12 | +{ |
| 13 | + private readonly IHttpContextAccessor _httpContextAccessor; |
| 14 | + private readonly IConfiguration _configuration; |
| 15 | + private string? _forcedTenantName; |
| 16 | + |
| 17 | + public DbSet<Employee> Employees => Set<Employee>(); |
| 18 | + |
| 19 | + public AppDbContext(IHttpContextAccessor httpContextAccessor, IConfiguration configuration) |
| 20 | + { |
| 21 | + _httpContextAccessor = httpContextAccessor; |
| 22 | + _configuration = configuration; |
| 23 | + } |
| 24 | + |
| 25 | + public void SetTenantName(string tenantName) |
| 26 | + { |
| 27 | + _forcedTenantName = tenantName; |
| 28 | + } |
| 29 | + |
| 30 | + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| 31 | + { |
| 32 | + string connectionString = GetConnectionString(); |
| 33 | + optionsBuilder.UseNpgsql(connectionString); |
| 34 | + } |
| 35 | + |
| 36 | + private string GetConnectionString() |
| 37 | + { |
| 38 | + string? tenantName = GetTenantName(); |
| 39 | + string connectionString = _configuration[$"Data:{tenantName ?? "Default"}Connection"]; |
| 40 | + |
| 41 | + if (connectionString == null) |
| 42 | + { |
| 43 | + throw GetErrorForInvalidTenant(tenantName); |
| 44 | + } |
| 45 | + |
| 46 | + string postgresPassword = Environment.GetEnvironmentVariable("PGPASSWORD") ?? "postgres"; |
| 47 | + return connectionString.Replace("###", postgresPassword); |
| 48 | + } |
| 49 | + |
| 50 | + private string? GetTenantName() |
| 51 | + { |
| 52 | + if (_forcedTenantName != null) |
| 53 | + { |
| 54 | + return _forcedTenantName; |
| 55 | + } |
| 56 | + |
| 57 | + if (_httpContextAccessor.HttpContext != null) |
| 58 | + { |
| 59 | + string? tenantName = (string?)_httpContextAccessor.HttpContext.Request.RouteValues["tenantName"]; |
| 60 | + |
| 61 | + if (tenantName == null) |
| 62 | + { |
| 63 | + throw GetErrorForInvalidTenant(null); |
| 64 | + } |
| 65 | + |
| 66 | + return tenantName; |
| 67 | + } |
| 68 | + |
| 69 | + return null; |
| 70 | + } |
| 71 | + |
| 72 | + private static JsonApiException GetErrorForInvalidTenant(string? tenantName) |
| 73 | + { |
| 74 | + return new JsonApiException(new ErrorObject(HttpStatusCode.BadRequest) |
| 75 | + { |
| 76 | + Title = "Missing or invalid tenant in URL.", |
| 77 | + Detail = $"Tenant '{tenantName}' does not exist." |
| 78 | + }); |
| 79 | + } |
| 80 | +} |
0 commit comments