Enterprise multi-tenancy often requires isolating database connections, feature flags, and branding per client while sharing a single application deployment codebase. Traditional multi-tenancy approaches rely on inflexible routing prefixes hardcoded into every controller attribute or complex middleware that intercepts requests post-routing, breaking standard MVC URL generation (Url.Action).
To achieve clean, first-class multi-tenancy without polluting controllers with tenant lookup boilerplate, modern ASP.NET Core MVC provides two powerful extensibility points: DynamicRouteValueTransformer (which evaluates and mutates route parameters at runtime) and IApplicationModelConvention (which programmatically inspects and modifies controller metadata, route templates, and filters at startup). This guide examines how to architect, implement, and test an end-to-end dynamic multi-tenant MVC pipeline.
1. Architectural Blueprint & Core Mechanics
Understanding the division of labor between startup-time conventions and runtime route transformers ensures optimal performance:
Component | Lifecycle Interface | Core Responsibility |
Application Model Convention | IApplicationModelConvention (Startup)
| Inspects the MVC controller graph at startup and dynamically applies tenant routing prefixes or global filters to all controllers. |
Dynamic Route Transformer | DynamicRouteValueTransformer (Per-Request)
| Intercepts inbound requests at runtime (inspecting subdomains, headers, or paths) to resolve tenant context and inject route values. |
Inbound HTTP Request (tenant1.enterprise.com)
│
▼
[TenantRouteTransformer] ──> Resolves Tenant from Subdomain / Header
│
▼
[Dynamic Routing Engine] ──> Injects "tenant" into RouteValueDictionary
│
▼
[IApplicationModelConvention] ──> Matches Route Template Prefix ({tenant})
│
▼
[Controller Action] ──> Receives Strongly Typed Tenant Context
2. The Tenant Context & Resolution Service
We define an immutable tenant record and a resolution service that queries a distributed cache or database to resolve tenant metadata based on the request's host header.
C#
public sealed record TenantDetails(
Guid TenantId,
string Identifier,
string CompanyName,
string ConnectionStringKey,
bool IsActive
);
public interface ITenantResolutionService
{
Task<TenantDetails?> ResolveTenantAsync(string hostName, CancellationToken cancellationToken = default);
}
public class TenantResolutionService : ITenantResolutionService
{
private readonly IMemoryCache _cache;
private readonly ILogger<TenantResolutionService> _logger;
public TenantResolutionService(IMemoryCache cache, ILogger<TenantResolutionService> logger)
{
_cache = cache;
_logger = logger;
}
public async Task<TenantDetails?> ResolveTenantAsync(string hostName, CancellationToken cancellationToken = default)
{
string cacheKey = $"tenant-domain-{hostName.ToLowerInvariant()}";
return await _cache.GetOrCreateAsync(cacheKey, async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
_logger.LogInformation("Resolving tenant mapping for host: {Host}", hostName);
// Simulate database or configuration lookup
await Task.CompletedTask;
return hostName.StartsWith("tenant1", StringComparison.OrdinalIgnoreCase)
? new TenantDetails(Guid.NewGuid(), "tenant1", "Acme Corporation", "Db_Tenant1", true)
: hostName.StartsWith("tenant2", StringComparison.OrdinalIgnoreCase)
? new TenantDetails(Guid.NewGuid(), "tenant2", "Globex Industries", "Db_Tenant2", true)
: null;
});
}
}
3. Implementing the Dynamic Route Transformer
The DynamicRouteValueTransformer intercepts incoming requests, examines the subdomain or headers, resolves the tenant context, and injects route values into the routing pipeline before controller activation.
C#
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
public class TenantRouteTransformer : DynamicRouteValueTransformer
{
private readonly ITenantResolutionService _tenantResolutionService;
private readonly ILogger<TenantRouteTransformer> _logger;
public TenantRouteTransformer(
ITenantResolutionService tenantResolutionService,
ILogger<TenantRouteTransformer> logger)
{
_tenantResolutionService = tenantResolutionService;
_logger = logger;
}
public override async ValueTask<RouteValueDictionary> TransformAsync(
HttpContext httpContext,
RouteValueDictionary values)
{
string host = httpContext.Request.Host.Host;
var tenant = await _tenantResolutionService.ResolveTenantAsync(host, httpContext.RequestAborted);
if (tenant is null || !tenant.IsActive)
{
_logger.LogWarning("Tenant resolution failed or inactive for host: {Host}", host);
values["controller"] = "Error";
values["action"] = "TenantNotFound";
return values;
}
// Store tenant in HttpContext items for downstream services/middleware
httpContext.Items["CurrentTenant"] = tenant;
// Inject resolved tenant identifier into route values
values["tenant"] = tenant.Identifier;
// Ensure default controller and action are populated if omitted
if (!values.ContainsKey("controller"))
{
values["controller"] = "Dashboard";
}
if (!values.ContainsKey("action"))
{
values["action"] = "Index";
}
return values;
}
}
4. Implementing IApplicationModelConvention
To avoid hardcoding {tenant} route templates on every single controller action across your application, an IApplicationModelConvention programmatically inspects and modifies the MVC application model at startup, automatically prepending the tenant routing token.
C#
using Microsoft.AspNetCore.Mvc.ApplicationModels;
public class TenantRouteConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
foreach (var controller in application.Controllers)
{
// Skip controllers explicitly opted out of multi-tenancy (e.g., Global Health checks)
if (controller.ControllerType.IsDefined(typeof(SkipTenantConventionAttribute), inherit: true))
{
continue;
}
foreach (var selector in controller.Selectors)
{
if (selector.AttributeRouteModel != null)
{
// Prepend the tenant route segment to existing attribute routes
selector.AttributeRouteModel.Template = "{tenant:required}/" + selector.AttributeRouteModel.Template.TrimStart('/');
}
else
{
// Fallback for convention-based routing
selector.AttributeRouteModel = new AttributeRouteModel
{
Template = "{tenant:required}/{controller}/{action}/{id?}"
};
}
}
}
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class SkipTenantConventionAttribute : Attribute { }
5. Programmatic Registration and Wiring (Program.cs)
Register your tenant convention, route transformer, and resolution services during application bootstrapping:
C#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<ITenantResolutionService, TenantResolutionService>();
builder.Services.AddScoped<TenantRouteTransformer>();
// Register MVC with our custom application model convention
builder.Services.AddControllersWithViews(options =>
{
options.Conventions.Add(new TenantRouteConvention());
});
var app = builder.Build();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// Map dynamic route transformer for multi-tenant handling
endpoints.MapDynamicControllerRoute<TenantRouteTransformer>("{tenant:required}/{controller=Dashboard}/{action=Index}/{id?}");
// Fallback standard route for non-tenant endpoints
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.Run();
6. Consuming Tenant Context in Controllers
With routing and conventions configured, controllers access the resolved tenant cleanly via HttpContext.Items or a scoped accessor service:
C#
using Microsoft.AspNetCore.Mvc;
[Route("")]
public class DashboardController : Controller
{
[HttpGet("")]
public IActionResult Index(string tenant)
{
var tenantDetails = HttpContext.Items["CurrentTenant"] as TenantDetails;
if (tenantDetails is null)
{
return NotFound("Tenant context missing.");
}
return View("Dashboard", new
{
TenantId = tenantDetails.TenantId,
CompanyName = tenantDetails.CompanyName,
RouteToken = tenant
});
}
}
Conclusion
By combining IApplicationModelConvention at startup to dynamically inject route prefixes and DynamicRouteValueTransformer at runtime to resolve tenant identity, you establish a robust, scalable multi-tenancy architecture in ASP.NET Core MVC. This approach eliminates repetitive routing boilerplate across controllers, preserves standard URL generation (Url.Action), and fully isolates tenant execution contexts cleanly and efficiently.
ASP.NET Core MVCmulti-tenancyDynamicRouteValueTransformerIApplicationModelConventionroutingtenant resolution
Join the conversation! Your thoughts help the community grow.