Suggestions for a simple multi-tenant design for .net core
I'm trying not to use any third party tools, just a very simple tenant based system that uses a different subdomain or domain name per tenant. I will create navigation properties on the Tenant entity to things like BlogPosts, EventPosts, etc. and map them to ViewModels in the controller. If a tenant is not found, I will forward to another website where the user can sign-up for a tenant account. I could cache the tenant provider lookup so it doesn't hit the database, but it's probably not needed for a small site.
Looking for any feedback on a design like the code below.
In Startup.cs
services.AddScoped<TenantProvider>();
TenantProvider.cs:
public class TenantProvider
{
private readonly ApplicationDbContext _dbContext;
private readonly IHttpContextAccessor _httpContextAccessor;
public Tenant CurrentTenant { get; set; }
public TenantProvider(ApplicationDbContext dbContext, IHttpContextAccessor httpContextAccessor)
{
_dbContext = dbContext;
_httpContextAccessor = httpContextAccessor;
ResolveTenant();
}
protected void ResolveTenant()
{
var subdomain = _httpContextAccessor.HttpContext.Request.Host.Value.ToLower();
var tenant = _dbContext.Tenants
.FirstOrDefault(t => t.DomainName.Equals(subdomain, StringComparison.OrdinalIgnoreCase)
|| t.SubdomainName.Equals(subdomain, StringComparison.OrdinalIgnoreCase));
CurrentTenant = tenant;
if (tenant == null)
{
_httpContextAccessor.HttpContext.Response.Redirect("https://www.google.com/");
}
}
}
In Home Controller:
private readonly Tenant tenant;
public HomeController(TenantProvider tenantProvider)
{
_emailSender = emailSender;
tenant = tenantProvider.CurrentTenant;
}
0 comments:
Post a Comment