.NET Generic Host Integration
MultiTenant works with any .NET application using dependency injection, not just ASP.NET Core. The .NET Generic Host app model — used by worker services, console apps, and background processes — is fully supported. This guide covers tenant resolution in non-web scenarios.
Package Installation
For Generic Host apps install the Finbuckle.MultiTenant core package:
dotnet add package Finbuckle.MultiTenant
If you also need per-tenant options, add Finbuckle.MultiTenant.Options. For
EF Core data isolation, add Finbuckle.MultiTenant.EntityFrameworkCore.
The
Finbuckle.MultiTenant.AspNetCorepackage is not required and should not be used — its strategies and middleware depend onHttpContext, which is unavailable in Generic Host apps.
How It Differs from ASP.NET Core
In ASP.NET Core, an ambient tenant scope begins automatically at the start of each request's pipeline, and the
UseMultiTenant<TId>() middleware sets the resolved tenant on it. In a Generic Host app there is no middleware. You must manually:
- Create a DI scope for each unit of work (message, job, iteration).
- Resolve the tenant within that scope using
ITenantResolver. - Begin an ambient tenant scope seeded with the resolved tenant via
IServiceProvider.BeginTenantScope(tenantInfo).
Once the ambient scope is established, per-tenant options, EF Core data isolation, and all tenant-aware services work identically to ASP.NET Core.
Configuring Services
Service registration is the same as any other app. Use AddMultiTenant<TTenantInfo, TId>() with strategies and stores
that work without HttpContext.
Compatible Strategies
These strategies from the core Finbuckle.MultiTenant package work in any host:
| Strategy | Usage |
|---|---|
| Delegate Strategy | Most common. Pass your message, job context, or arbitrary object. |
| Static Strategy | Useful as a fallback or default tenant. |
Custom IMultiTenantStrategy |
Implement your own for full control. |
Strategies from Finbuckle.MultiTenant.AspNetCore (Host, Route, Base Path, Header, Claim, Session, HttpContext)
rely on HttpContext and are not compatible.
Compatible Stores
All stores work in Generic Host apps:
- Configuration Store
- In-Memory Store
- EFCore Store
- Http Remote Store
- Distributed Cache Store
- Echo Store
- Custom
IMultiTenantStore
Example: Queue Processor Registration
using Finbuckle.MultiTenant;
var builder = Host.CreateApplicationBuilder(args);
// Register MultiTenant services with a delegate strategy.
// The delegate receives whatever object you pass to TenantResolver.ResolveAsync().
builder.Services.AddMultiTenant<TenantInfo, string>()
.WithDelegateStrategy(async context =>
{
if (context is QueueMessage message)
return message.TenantId;
return null;
})
.WithStaticStrategy("default-tenant") // fallback
.WithConfigurationStore();
// Register your message handler.
builder.Services.AddScoped<IMessageHandler, MessageHandler>();
Example: Console App Registration
using Finbuckle.MultiTenant;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddMultiTenant<TenantInfo, string>()
.WithDelegateStrategy(async ctx =>
{
// ctx is whatever you pass in
return ctx as string; // e.g., tenant identifier string
})
.WithInMemoryStore();
var provider = services.BuildServiceProvider();
await using var scope = provider.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<TenantManager<TenantInfo, string>>()
.AddAsync(new TenantInfo
{
Id = Guid.NewGuid().ToString(),
Identifier = "tenant-a"
});
Resolving a Tenant
Resolution is a two-step process:
- Call
ITenantResolver.ResolveAsync(context)to determine the tenant. It returns the resolvedTenantInfo(theTTenantInfoinstance) ornullif no tenant was resolved. - If a tenant was resolved, begin an ambient scope seeded with it via
BeginTenantScope(tenantInfo).
Worker Service Pattern (One Tenant per Message)
The most common Generic Host pattern: create a scope per message, resolve the tenant, and process within that scope.
public class QueueProcessor : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public QueueProcessor(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var message = await ReceiveMessageAsync(stoppingToken);
// Each message gets its own scope and tenant.
await using var scope = _scopeFactory.CreateAsyncScope();
var services = scope.ServiceProvider;
// 1. Resolve tenant for this message.
var resolver = services.GetRequiredService<ITenantResolver<TenantInfo, string>>();
var tenantInfo = await resolver.ResolveAsync(message);
// 2. Begin an ambient tenant scope seeded with the resolved tenant.
if (tenantInfo is not null)
services.BeginTenantScope(tenantInfo);
// 3. Process within the ambient tenant scope.
var handler = services.GetRequiredService<IMessageHandler>();
await handler.HandleAsync(message, stoppingToken);
}
}
private async Task<QueueMessage> ReceiveMessageAsync(CancellationToken ct)
{
// Your queue receive logic here.
throw new NotImplementedException();
}
}
Console App Pattern (Single Tenant at Startup)
For apps that resolve the tenant once at startup, create a scope and use it for the app's lifetime:
using Finbuckle.MultiTenant;
var services = new ServiceCollection();
services.AddMultiTenant<TenantInfo, string>()
.WithDelegateStrategy(async ctx => ctx as string)
.WithInMemoryStore();
var provider = services.BuildServiceProvider();
// Create a scope for the app lifetime.
using var scope = provider.CreateScope();
var scopedProvider = scope.ServiceProvider;
await scopedProvider.GetRequiredService<TenantManager<TenantInfo, string>>()
.AddAsync(new TenantInfo { Id = "tenant-a-id", Identifier = "tenant-a" });
// Resolve the tenant and begin an ambient scope seeded with it.
var resolver = scopedProvider.GetRequiredService<ITenantResolver<TenantInfo, string>>();
var tenantInfo = await resolver.ResolveAsync("tenant-a");
if (tenantInfo is not null)
scopedProvider.BeginTenantScope(tenantInfo);
// All services resolved from scopedProvider now see the tenant.
var options = scopedProvider.GetRequiredService<IOptions<MyOptions>>();
Console.WriteLine($"Tenant: {tenantInfo?.Identifier}");
Handling Unresolved Tenants
If no strategy produces an identifier or no store finds a match, ResolveAsync returns null.
Check for null before beginning the tenant scope:
var tenantInfo = await resolver.ResolveAsync(message);
if (tenantInfo is not null)
{
services.BeginTenantScope(tenantInfo);
}
else
{
// Handle unresolved: log, skip, use fallback, etc.
_logger.LogWarning("No tenant resolved for message {MessageId}", message.Id);
continue;
}
Running Work as a Tenant
IServiceProvider.RunInTenantScopeAsync(tenantInfo, action) combines the steps above into one call. It creates a new
DI scope, begins an ambient tenant scope for tenantInfo, passes the new scope's IServiceProvider to your delegate,
and disposes the DI scope when the delegate finishes, even if it throws. The caller's own tenant scope, or lack of
one, is unchanged when it returns. See
Configuration and Usage for the full description.
Example: Process Each Message as Its Tenant
The worker pattern above, rewritten with RunInTenantScopeAsync. The tenant is resolved in a short-lived scope, then
the message is handled in a fresh scope for that tenant:
public class QueueProcessor(IServiceProvider services, IServiceScopeFactory scopeFactory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var message = await ReceiveMessageAsync(stoppingToken);
TenantInfo? tenantInfo;
await using (var resolveScope = scopeFactory.CreateAsyncScope())
{
var resolver = resolveScope.ServiceProvider.GetRequiredService<ITenantResolver<TenantInfo, string>>();
tenantInfo = await resolver.ResolveAsync(message);
}
if (tenantInfo is null)
continue;
await services.RunInTenantScopeAsync(tenantInfo, scoped =>
scoped.GetRequiredService<IMessageHandler>().HandleAsync(message, stoppingToken));
}
}
// ReceiveMessageAsync as in the earlier example.
}
Example: Run a Job for Every Tenant
A scheduled job that runs once for each tenant. Each tenant gets its own DI scope, so its DbContext and per-tenant
options are separate from every other tenant's:
public class NightlyCleanup(IServiceProvider services, ILogger<NightlyCleanup> logger)
{
public async Task RunAsync(CancellationToken cancellationToken)
{
IEnumerable<TenantInfo> tenants;
await using (var scope = services.CreateAsyncScope())
{
tenants = await scope.ServiceProvider
.GetRequiredService<TenantManager<TenantInfo, string>>()
.GetAllAsync(cancellationToken);
}
foreach (var tenant in tenants)
{
var removed = await services.RunInTenantScopeAsync(tenant, async scoped =>
{
var db = scoped.GetRequiredService<AppDbContext>();
var cutoff = DateTime.UtcNow.AddDays(-30);
return await db.AuditEntries.Where(e => e.CreatedUtc < cutoff)
.ExecuteDeleteAsync(cancellationToken);
});
logger.LogInformation("Removed {Count} audit entries for {Tenant}", removed, tenant.Identifier);
}
}
}
Runs for different tenants can also execute concurrently, for example with Task.WhenAll or Parallel.ForEachAsync;
each run keeps its own tenant.
Using TenantResolver Events
The same resolution events available in ASP.NET Core work in Generic Host apps. Configure them when registering services:
builder.Services.AddMultiTenant<TenantInfo, string>()
.WithDelegateStrategy(async ctx => /* ... */)
.WithConfigurationStore()
.WithPerTenantOptions(); // enables options
// Hook into resolution events.
builder.Services.Configure<MultiTenantOptions<TenantInfo, string>>(options =>
{
options.Events.OnTenantResolveCompleted = context =>
{
_logger.LogInformation(
"Tenant resolved: {TenantId} via strategy {Strategy}",
context.TenantContext.TenantInfo?.Id,
context.Strategy.GetType().Name);
return Task.CompletedTask;
};
});
Per-Tenant Options
Per-tenant options work in Generic Host apps just as they do in ASP.NET Core. The only requirement
is that ITenantContext.TenantInfo is populated within the current scope. Once set, IOptions<T>,
IOptionsSnapshot<T>, and IOptionsMonitor<T> all return values for the current tenant.
// Register per-tenant options.
builder.Services.ConfigurePerTenant<MyOptions, TenantInfo, string>((options, tenantInfo) =>
{
options.Setting = tenantInfo.Identifier;
});
// In your handler, resolved within a tenant scope:
public class MessageHandler : IMessageHandler
{
public MessageHandler(IOptionsSnapshot<MyOptions> options)
{
// options.Value reflects the current tenant's settings.
}
}
EF Core Data Isolation
EF Core data isolation works identically in Generic Host apps. After ITenantContext is populated:
AddMultiTenantDbContext<T, TId>()andAddPooledMultiTenantDbContext<T, TId>()automatically bindTenantInfo.- Global query filters enforce per-tenant data separation.
IMultiTenantDbContext.TenantInforeflects the current tenant.
builder.Services.AddMultiTenantDbContext<AppDbContext, string>(options =>
options.UseSqlServer(connectionString));
When using
AddPooledMultiTenantDbContext, only the scoped tenant context is rebound. Pooled context instances are reused, soOnConfiguringis called only once. UseAddMultiTenantDbContextif connection strings or providers vary per tenant.
Important Considerations
TenantInfocan only be set once per scope. If your worker might encounter multiple circumstances where a tenant could be set, useITenantContext.IsResolvedto check first, or use a fresh scope each time.RunInTenantScopeAsyncgives each unit of work a fresh scope for you.ITenantResolver.ResolveAsync()returns a newTenantContext— it does not automatically populate the scoped one. You must copyTenantInfoyourself.IOptionsMonitor<T>is scoped in MultiTenant (unlike standard .NET where it is a singleton). Despite the scoped registration, it preserves the same change-notification and cache-invalidation behavior as the standard implementation. See Per-Tenant Options for details.- No authentication integration. Per-tenant authentication and
WithPerTenantAuthentication()requireFinbuckle.MultiTenant.AspNetCoreand ASP.NET Core's authentication middleware.
See Also
- Configuration and Usage — registration and resolver details
- Core Concepts —
ITenantContextand the ambient tenant scope - MultiTenant Strategies — all built-in strategies
- Per-Tenant Options — options customization
- EF Core Data Isolation — shared and separate database patterns