Kanject.Core.Tenancy
4.0.0
Prefix Reserved
dotnet add package Kanject.Core.Tenancy --version 4.0.0
NuGet\Install-Package Kanject.Core.Tenancy -Version 4.0.0
<PackageReference Include="Kanject.Core.Tenancy" Version="4.0.0" />
<PackageVersion Include="Kanject.Core.Tenancy" Version="4.0.0" />
<PackageReference Include="Kanject.Core.Tenancy" />
paket add Kanject.Core.Tenancy --version 4.0.0
#r "nuget: Kanject.Core.Tenancy, 4.0.0"
#:package Kanject.Core.Tenancy@4.0.0
#addin nuget:?package=Kanject.Core.Tenancy&version=4.0.0
#tool nuget:?package=Kanject.Core.Tenancy&version=4.0.0
Kanject.Core.Tenancy
Kanject Tenancy — the minimal contract every multi-tenant Kanject service shares: a single scoped ITenantContext that answers "which tenant is this request for?", plus the one canonical header name everything agrees on.
Installation
dotnet add package Kanject.Core.Tenancy
Targets .NET 9, .NET 10 and .NET 11. The package has no dependencies and is Native AOT / trimming compatible. Kanject.Core.Api and Kanject.Core.ApiV2 already reference it, so ASP.NET Core services using either get it transitively.
⚠️ The Problem
Multi-tenancy leaks tenant identity into every layer, and without a shared contract it does so inconsistently:
- The tenant ID is resolved a dozen different ways. One handler reads a JWT claim, another a route value, a third an
x-tenantheader, a fourthX-TenantId. Casing and header names drift, and the data layer can't trust any single source. - Tenant identity gets threaded by hand. Passing a
tenantIdstring down through service → repository → query is noisy, easy to forget, and trivially mis-wired (last week's tenant captured in a closure, the wrong overload called). - The header name is a magic string.
"x-tenant-id"ends up hard-coded in the gateway, the middleware, the integration tests, and the docs — each a separate place to typo, each drifting independently. - The persistence layer has no contract to bind to. A repository that wants to scope every query to the current tenant needs something stable to depend on — not an
HttpContextit shouldn't see, and not a constructorstringit can't get from DI.
🛠️ The Solution
Two tiny, dependency-free pieces:
| Piece | Namespace | Purpose |
|---|---|---|
ITenantContext |
Kanject.Core.Tenancy |
The one scoped service that exposes string TenantId — the single source of truth for the current tenant |
TenantConstants |
Kanject.Core.Tenancy.Constants |
TenantHeaderName = "x-tenant-id" — the canonical header, as a constant instead of a magic string |
The key principle: resolve the tenant once, at the edge, into a scoped ITenantContext; everything downstream depends on the interface, never on where the ID came from. Swap header-based resolution for a JWT claim without touching a single repository.
📖 Use Cases & Examples
1. Use the ready-made ASP.NET Core middleware
This package is the contract only. For HTTP services, Kanject.Core.Api (and Kanject.Core.ApiV2) provide the implementation. AddTenantMiddleware() registers a scoped ITenantContext, and UseTenantMiddleware() fills it from the x-tenant-id request header:
using Kanject.Core.Api.Extensions;
builder.Services.AddTenantMiddleware();
var app = builder.Build();
app.UseAuthentication();
app.UseTenantMiddleware(); // after authentication, before tenant-aware services run
app.UseAuthorization();
When the header is missing or blank, the middleware leaves TenantId empty, so tenant-neutral endpoints keep working. Services that require a tenant must check for that (see example 4).
2. Implement and register your own context
For any other edge (Lambda, a queue worker, a non-header HTTP scheme), implement ITenantContext yourself and register it scoped so each request/invocation gets its own tenant.
using Kanject.Core.Tenancy;
using Kanject.Core.Tenancy.Constants;
public sealed class HttpTenantContext : ITenantContext
{
public HttpTenantContext(IHttpContextAccessor accessor)
{
// Resolve from the canonical header — no magic string.
TenantId = accessor.HttpContext?
.Request.Headers[TenantConstants.TenantHeaderName]
.ToString() ?? string.Empty;
}
public string TenantId { get; }
}
// Startup — scoped, so it never bleeds across requests.
services.AddHttpContextAccessor();
services.AddScoped<ITenantContext, HttpTenantContext>();
3. Resolve from a JWT claim instead (no downstream changes)
Because everything depends on the interface, the resolution strategy is a single swap:
public sealed class ClaimsTenantContext(IHttpContextAccessor accessor) : ITenantContext
{
public string TenantId =>
accessor.HttpContext?.User.FindFirst("tenant_id")?.Value ?? string.Empty;
}
services.AddScoped<ITenantContext, ClaimsTenantContext>();
4. Consume it downstream
Inject ITenantContext wherever a tenant boundary matters — services, repositories, query builders — and let DI hand you the right scoped instance. IOrderStore below is a placeholder for your own data-access abstraction:
using Kanject.Core.Tenancy;
// Hypothetical data-access abstraction — stands in for whatever your app uses.
public interface IOrderStore
{
Task<IReadOnlyList<Order>> ListForTenantAsync(string tenantId, CancellationToken ct);
}
public sealed class OrderRepository(ITenantContext tenant, IOrderStore store)
{
public Task<IReadOnlyList<Order>> ListAsync(CancellationToken ct)
{
if (string.IsNullOrEmpty(tenant.TenantId))
throw new InvalidOperationException("No tenant resolved for this request.");
// Scope every query to the current tenant — partition key, filter, etc.
return store.ListForTenantAsync(tenant.TenantId, ct);
}
}
5. The header name, everywhere
Reference TenantConstants.TenantHeaderName from middleware, gateways, outbound clients, and tests so there is exactly one spelling of "x-tenant-id" in the system.
using Kanject.Core.Tenancy.Constants;
// Propagating the tenant to a downstream service call:
httpClient.DefaultRequestHeaders.Add(TenantConstants.TenantHeaderName, tenant.TenantId);
🧪 Testing
Because ITenantContext is a one-property interface, tests need no HTTP, no DI container, and no header plumbing — hand-roll a stub:
file sealed class FixedTenant(string id) : ITenantContext
{
public string TenantId => id;
}
[Fact]
public async Task Repository_Scopes_To_Current_Tenant()
{
var repo = new OrderRepository(new FixedTenant("acme"), fakeStore);
var orders = await repo.ListAsync(CancellationToken.None);
Assert.All(orders, o => Assert.Equal("acme", o.TenantId));
}
🏗️ Design notes
- Contract only — no implementation. This package deliberately ships zero resolution logic. The edge (HTTP, Lambda, message envelope) is where tenant identity lives, and that's host-specific; binding the contract to
HttpContextwould couple every consumer to ASP.NET Core. You provide the implementation (or use theKanject.Core.Apimiddleware); this package provides the seam. - Scoped lifetime is the contract's expectation. A singleton
ITenantContextwould bleed one request's tenant into another — the same class of cross-request state-sharing bug that affects any per-unit collaborator registered as a singleton. Register it scoped. TenantIdis non-null by interface. Implementations should returnstring.Empty(notnull) when no tenant is resolvable, and tenant-scoped operations should reject empty up front rather than silently querying across tenants.
Related packages
| Package | Role | Availability |
|---|---|---|
Kanject.Core.Api |
ASP.NET Core edge conventions, including AddTenantMiddleware() / UseTenantMiddleware(), which populate ITenantContext from the x-tenant-id header |
nuget.org |
Kanject.Core.ApiV2 |
Same tenant middleware for the V2 API package | nuget.org |
Kanject.Core.NoSqlDatabase.Provider.DynamoDb |
DynamoDB provider; its generated [MultiTenant] repositories take an ITenantContext and scope data by TenantId |
Commercial license (not on nuget.org) |
License
Licensed under the Kanject Code Libraries License Agreement (KCLLA); the full text ships in this package as LICENSE.md. Organizations whose trailing-twelve-month gross revenue and total funding raised are each below US$250,000 may use it at no cost under the Free Tier. At or above either threshold a commercial license is required — contact commercial@kanjectbusiness.com.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- No dependencies.
-
net11.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Kanject.Core.Tenancy:
| Package | Downloads |
|---|---|
|
Kanject.Core.Api
Kanject core api |
|
|
Kanject.Core.ApiV2
Kanject core api V2 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.0.0 | 151 | 11/11/2026 |
| 3.12.1 | 816 | 9/27/2026 |
| 3.12.0 | 139 | 9/27/2026 |
| 3.11.7 | 137 | 9/26/2026 |
| 3.11.6 | 190 | 9/7/2026 |
| 3.11.5 | 166 | 8/27/2026 |
| 3.11.4 | 158 | 8/22/2026 |
| 3.11.3 | 183 | 8/10/2026 |
| 3.11.2 | 160 | 8/9/2026 |
| 3.11.1 | 166 | 8/5/2026 |
| 3.11.0 | 159 | 8/5/2026 |
| 3.10.0 | 173 | 8/3/2026 |
| 3.9.7 | 174 | 7/30/2026 |
| 3.9.6 | 185 | 7/18/2026 |
| 3.9.5 | 150 | 7/13/2026 |
| 3.9.4 | 181 | 7/11/2026 |
| 3.9.3 | 140 | 7/11/2026 |
| 3.9.2 | 286 | 7/9/2026 |
- Adds .NET 11 (net11.0) as a target framework.
- Removes .NET 8 (net8.0) as a target framework.