# Getting started

The docs of Tenantry 0.7 (Core v0.7.0, Pro v0.7.0), the newest release. Web page: https://tenantry.dev/docs/pro/getting-started

This 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](https://tenantry.dev/docs/pro/schema-per-tenant.md) and
[Database providers](https://tenantry.dev/docs/pro/database-providers.md).

## 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](https://tenantry.dev/docs/pro/installation.md), which also covers CI and the licence key. For
an ASP.NET Core app using SQL Server:

```bash
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.SqlServer
```

`Tenantry.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](https://tenantry.dev/docs/pro/database-providers.md#mysql)).

## 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:

```csharp
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](https://tenantry.dev/docs/pro/migration-orchestration.md#which-tenants-are-migrated)). Stop work for a suspended tenant with Tenantry
> Core's `ValidateTenantActivity` instead ([Suspended tenants](https://tenantry.dev/docs/pro/background-jobs.md#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:

```csharp
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

```csharp
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

```csharp
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](https://tenantry.dev/docs/core/access-control.md)). Run the application with
`migrate-tenants` once per deployment, before the new version serves requests, to migrate every tenant's
database (see [Tenant migrations](https://tenantry.dev/docs/pro/migration-orchestration.md)).

## 5. Provide a licence key

Pro needs your licence key, from your [Pro access page](https://tenantry.dev/dashboard/pro). `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`](https://tenantry.dev/docs/pro/api/tenantry-pro-licenserequiredexception.md)). 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](https://tenantry.dev/docs/pro/licensing.md).

## Where to go next

- [Schema per tenant](https://tenantry.dev/docs/pro/schema-per-tenant.md): a schema per tenant in one database.
- [Mixed mode](https://tenantry.dev/docs/pro/mixed-mode.md): dedicated and shared tenants in one application.
- [Tenant lifecycle](https://tenantry.dev/docs/pro/tenant-lifecycle.md): create, migrate and seed a tenant in one call.
- [Database providers](https://tenantry.dev/docs/pro/database-providers.md): PostgreSQL and MySQL.
- [Background jobs & non-HTTP hosts](https://tenantry.dev/docs/pro/background-jobs.md): workers and console applications.
