這樣做:使用中間件。我不確定下面的代碼是否100%好。但是你可以看到它是如何完成的。
啓動類:
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseTenantResolver();
}
using Microsoft.AspNet.Builder;
namespace Multitenant
{
public static class TenantResolverMiddlewareAppBuilderExtensions
{
public static void UseTenantResolver(this IApplicationBuilder builder)
{
builder.UseMiddleware<TenantResolverMiddleware>();
}
}
}
namespace Multitenant
{
public class TenantResolverMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public TenantResolverMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<TenantResolverMiddleware>();
}
public async Task Invoke(HttpContext context)
{
using (_logger.BeginScope("TenantResolverMiddleware"))
{
var tenant = new Tenant
{
Id = "tenant1" // todo: determine this based on HttpContext etc.
};
_logger.LogInformation(string.Format("Resolved tenant. Current tenant: {0}", tenant.Id));
var tenantFeature = new TenantFeature(tenant);
context.Features.Set<ITenantFeature>(tenantFeature);
await _next(context);
}
}
}
}