PM> Install-Package Autofac.AspNetCore.Extensions
> dotnet add package Autofac.AspNetCore.Extensions
- Autofac.Extensions.DependencyInjection
- Autofac.Multitenant
- Autofac.AspNetCore.Multitenant
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseAutofac()
.UseStartup<Startup>();
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseAutofac()
.UseStartup<Startup>();
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHttpContextAccessor();
services.AddScoped<ITenantIdentificationStrategy, SubdomainIdentificationStrategy>();
})
.UseAutofacMultitenant()
.UseStartup<Startup>();
public class SubdomainIdentificationStrategy : ITenantIdentificationStrategy
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SubdomainIdentificationStrategy(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public bool TryIdentifyTenant(out object tenantId)
{
var context = _httpContextAccessor.HttpContext;
if(context == null)
{
tenantId = null;
return false;
}
tenantId = GetSubDomain(context);
return tenantId != null;
}
private string GetSubDomain(HttpContext httpContext)
{
var subDomain = string.Empty;
var host = httpContext.Request.Host.Host;
if (!string.IsNullOrWhiteSpace(host))
{
subDomain = host.Split('.')[0];
}
return subDomain.Trim().ToLower();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.ConfigureServices(services =>
{
services.AddHttpContextAccessor();
services.AddScoped<ITenantIdentificationStrategy, SubdomainIdentificationStrategy>();
})
.UseAutofacMultitenant()
.UseStartup<Startup>();
});
public class SubdomainIdentificationStrategy : ITenantIdentificationStrategy
{
private readonly IHttpContextAccessor _httpContextAccessor;
public SubdomainIdentificationStrategy(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public bool TryIdentifyTenant(out object tenantId)
{
var context = _httpContextAccessor.HttpContext;
if(context == null)
{
tenantId = null;
return false;
}
tenantId = GetSubDomain(context);
return tenantId != null;
}
private string GetSubDomain(HttpContext httpContext)
{
var subDomain = string.Empty;
var host = httpContext.Request.Host.Host;
if (!string.IsNullOrWhiteSpace(host))
{
subDomain = host.Split('.')[0];
}
return subDomain.Trim().ToLower();
}
}
- Dave Ikin - davidikin45
This project is licensed under the MIT License