Docs
Tenantry CoreAPI reference

ConnectionStringExtensions class

Namespace: Tenantry.Core.Extensions · Package: Tenantry.Core · API reference

Registers per-tenant connection strings: TenantConnectionStringOptions<TKey> and ITenantConnectionStringResolver<TKey>.

public static class ConnectionStringExtensions

Methods

AddTenantConnectionStrings<TKey>(IServiceCollection, Action<TenantConnectionStringOptions<TKey>>)

The IServiceCollection form of ConnectionStringExtensions.UseConnectionStrings<TKey>, for code that has no ITenantBuilder<TKey>. Also registers the core Tenantry services.

public static IServiceCollection AddTenantConnectionStrings<TKey>(this IServiceCollection services, Action<TenantConnectionStringOptions<TKey>> configure) where TKey : IEquatable<TKey>, IParsable<TKey>

Type parameters:

  • TKey: The tenant identifier type.

Parameters:

  • services IServiceCollection: The application's service collection.
  • configure Action<TenantConnectionStringOptions<TKey>>: Sets the delegates that return a tenant's connection string.

Returns: IServiceCollection

Exceptions:

  • InvalidOperationException: Neither delegate is set after configure runs.

Calling it again configures the same options instance, so a later call can replace a delegate.

UseConnectionStrings<TKey>(ITenantBuilder<TKey>, Action<TenantConnectionStringOptions<TKey>>)

Configures how each tenant's connection string is found and registers ITenantConnectionStringResolver<TKey> as a singleton.

public static ITenantBuilder<TKey> UseConnectionStrings<TKey>(this ITenantBuilder<TKey> builder, Action<TenantConnectionStringOptions<TKey>> configure) where TKey : IEquatable<TKey>, IParsable<TKey>

Type parameters:

  • TKey: The tenant identifier type.

Parameters:

  • builder ITenantBuilder<TKey>: The tenant builder.
  • configure Action<TenantConnectionStringOptions<TKey>>: Sets the delegates that return a tenant's connection string.

Returns: ITenantBuilder<TKey>

builder.Services.AddTenantry<string>(tenant =>
{
    tenant.ResolveFromHeader("X-Tenant-Id");
    tenant.UseStore<AppTenantStore>();
    tenant.UseConnectionStrings(options =>
        options.GetConnectionString = t => $"Server=db;Database=app_{t.TenantId};Integrated Security=true");
});

builder.Services.AddDbContext<AppDbContext>((sp, options) =>     options.UseSqlServer(sp.GetRequiredService<ITenantConnectionStringResolver<string>>().Resolve())); ```

On this page