Getting started
View as MarkdownThis guide builds a database-per-tenant ASP.NET Core app on SQL Server: resolve the tenant, give each tenant its own database, provision new databases, and migrate every tenant database as a deployment step. Schema per tenant and the other providers follow the same shape; see Schema per tenant and Database providers.
1. Install the packages
Tenantry.Pro sits on top of Tenantry core, so you install both. The Pro packages come from a private feed: set it up first with Installation, which also covers CI and the licence key. For an ASP.NET Core app using SQL Server:
dotnet add package Tenantry.AspNetCore # Tenantry core: resolution + middleware
dotnet add package Tenantry.Pro # Pro: strategies + licensing
dotnet add package Tenantry.Pro.EfCore # provisioning, migrations, health checks
dotnet add package Microsoft.EntityFrameworkCore.SqlServerTenantry.Pro.EfCore also covers schema per tenant, audit logging and health checks. For PostgreSQL or MySQL, add
that EF Core provider in place of SQL Server's (Npgsql.EntityFrameworkCore.PostgreSQL, or
a MySQL provider).
2. Define your tenant store and DbContext
The tenant store, from Tenantry core, says which tenants exist. A production application usually backs it with a database; here is the shape:
using Tenantry;
public sealed class MyTenantStore : ITenantStore<string>
{
private static readonly ITenantDescriptor<string>[] Tenants =
[
new TenantDescriptor<string> { TenantId = "acme", Name = "Acme" },
new TenantDescriptor<string> { TenantId = "globex", Name = "Globex" },
];
public ValueTask<ITenantDescriptor<string>?> GetTenantAsync(string tenantId, CancellationToken ct = default)
=> ValueTask.FromResult(Tenants.FirstOrDefault(t => t.TenantId == tenantId));
public ValueTask<IReadOnlyList<ITenantDescriptor<string>>> GetAllTenantsAsync(CancellationToken ct = default)
=> ValueTask.FromResult<IReadOnlyList<ITenantDescriptor<string>>>(Tenants);
}Return every tenant from the store, suspended ones included: migrations reach only the tenants it lists (why). Stop work for a suspended tenant with Tenantry Core's
ValidateTenantActivityinstead (Suspended tenants).
Your DbContext is a plain EF Core context. With a database per tenant the connection string already points at the
tenant's database, so the context needs no per-tenant code:
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
}
public sealed class Order
{
public int Id { get; set; }
public string Description { get; set; } = "";
}3. Register Tenantry and Tenantry.Pro
using Microsoft.EntityFrameworkCore;
using Tenantry;
using Tenantry.Pro;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTenantry<string>(tenant =>
{
// From Tenantry core: how the tenant is identified, where tenants are defined, and each tenant's database.
tenant.ResolveFromHeader("X-Tenant-Id");
tenant.UseStore<MyTenantStore>();
tenant.UseConnectionStrings(opts =>
opts.GetConnectionString = t =>
$"Server=.;Database=app_{t.TenantId};Integrated Security=true;TrustServerCertificate=True");
// Tenantry.Pro features.
tenant.UsePro(pro => pro
.AddDatabaseProvisioning<AppDbContext>() // provisioning a new tenant creates its database...
.AddMigrations<AppDbContext>()); // ...then migrates it, through AppDbContext
// From Tenantry core: each AppDbContext connects to the current tenant's database.
tenant.AddDbContextPerTenantDatabase<AppDbContext>((sp, options) => options.UseSqlServer());
});4. Wire the request pipeline
await using var app = builder.Build();
// dotnet run -- migrate-tenants: migrate every tenant's database as a deployment step, then exit.
if (await app.RunTenantMigrationsIfRequestedAsync(args) is { } exitCode)
return exitCode;
app.UseTenantry(); // Tenantry core: resolves the tenant and opens the scope for the request
app.MapGet("/orders", (AppDbContext db) => db.Orders.ToListAsync());
// An administrator's operation: protect it with a policy of your own.
app.MapPost("/tenants/{id}/provision",
async (string id, ITenantStore<string> store, ITenantProvisioner<string> provisioner, CancellationToken ct) =>
{
// Add the tenant to your store first; provisioning creates its database and migrates it.
if (await store.GetTenantAsync(id, ct) is not { } tenant)
return Results.NotFound();
var result = await provisioner.ProvisionAsync(tenant, ct);
return result.Succeeded ? Results.Ok() : Results.StatusCode(StatusCodes.Status500InternalServerError);
}).RequireAuthorization("TenantAdmin");
app.Run();
return 0;A request with header X-Tenant-Id: acme now reads and writes app_acme, and X-Tenant-Id: globex hits
app_globex. The header is whatever the client sends, though, so in a real application authenticate requests and
check the caller may use the tenant, for example with tenant.ValidateTenantAccessByClaim("tenant_id") (Tenantry
core's access control). Run the application with
migrate-tenants once per deployment, before the new version serves requests, to migrate every tenant's
database (see Tenant migrations).
5. Provide a licence key
Pro needs your licence key, from your Pro access page. UsePro reads it
from the Tenantry:License setting, so it needs no code. The key does not expire, so you set it once. Without a
valid key the application does not start (LicenseRequiredException). Keep the key out of source control (in
user secrets, or the Tenantry__License environment variable), give it to CI as a secret, and set it in every
environment, production included. See Licensing.
Where to go next
- Schema per tenant: a schema per tenant in one database.
- Mixed mode: dedicated and shared tenants in one application.
- Tenant lifecycle: create, migrate and seed a tenant in one call.
- Database providers: PostgreSQL and MySQL.
- Background jobs & non-HTTP hosts: workers and console applications.