Corner49.Infra.AzureCosmosDB
10.0.169
dotnet add package Corner49.Infra.AzureCosmosDB --version 10.0.169
NuGet\Install-Package Corner49.Infra.AzureCosmosDB -Version 10.0.169
<PackageReference Include="Corner49.Infra.AzureCosmosDB" Version="10.0.169" />
<PackageVersion Include="Corner49.Infra.AzureCosmosDB" Version="10.0.169" />
<PackageReference Include="Corner49.Infra.AzureCosmosDB" />
paket add Corner49.Infra.AzureCosmosDB --version 10.0.169
#r "nuget: Corner49.Infra.AzureCosmosDB, 10.0.169"
#:package Corner49.Infra.AzureCosmosDB@10.0.169
#addin nuget:?package=Corner49.Infra.AzureCosmosDB&version=10.0.169
#tool nuget:?package=Corner49.Infra.AzureCosmosDB&version=10.0.169
Corner49.Infra.AzureCosmosDB
Opinionated repository layer for Azure Cosmos DB (NoSQL API). Part of Corner49.Infra – a set of packages that provide opinionated tooling for infrastructure in .NET applications.
- One
DocumentRepo<T>per container, with point reads, LINQ and SQL queries, paging, streaming, patching, bulk operations and change feed - Databases and containers are created at startup when they do not exist
- One shared
CosmosClientper connection string System.Text.Jsonserialisation with camelCase names- Built-in retry on
429/408, and RU pressure monitoring for heavy jobs
dotnet add package Corner49.Infra.AzureCosmosDB
Already included when you install Corner49.Infra.
Configuration
{
"CosmosDB": {
"ConnectString": "AccountEndpoint=https://...;AccountKey=...;",
"DatabaseName": "data",
"DirectMode": false
}
}
| Key | Default | Meaning |
|---|---|---|
ConnectString |
– | Cosmos DB account connection string |
DatabaseName |
data |
Default database for repos that do not name one |
DirectMode |
false |
true uses direct (TCP) connections, false uses gateway mode |
Getting started
1. Define a repository
using Corner49.Infra.DB;
public interface IOrderRepo {
Task<Order?> Get(string customerId, string id);
Task<QueryResult<Order>> Open(string customerId, string? continuationToken);
Task Save(Order order);
}
public class OrderRepo : IOrderRepo, IDocumentRepoInitializer {
private readonly DocumentRepo<Order> _repo;
public OrderRepo(IDocumentDB db) {
// container name, then the partition key path(s)
_repo = db.GetRepo<Order>("Orders", "customerId");
}
Task IDocumentRepoInitializer.Init() => _repo.Init();
public Task<Order?> Get(string customerId, string id) => _repo.GetItem(customerId, id);
public Task<QueryResult<Order>> Open(string customerId, string? continuationToken) =>
_repo.Query(customerId, q => q.Where(o => o.Status == "open"), continuationToken, maxItemCount: 50);
public Task Save(Order order) => _repo.UpsertItem(order.CustomerId, order);
}
IDocumentRepoInitializer.Init() is called for every registered repo at startup; DocumentRepo<T>.Init() creates the database and container when they are missing.
2. Register it
With an infra builder (Corner49.Infra or Corner49.Infra.CLI):
infra.AddDocumentDB(db => {
db.Configure = cfg => cfg.DatabaseName = "shop"; // optional override of the configuration
db.AddRepo<IOrderRepo, OrderRepo>();
});
With a plain IServiceCollection:
var db = services.AddDocumentDB(configuration, b => b.AddRepo<IOrderRepo, OrderRepo>());
// after the host is built:
await db.Init(app.Services);
Or without dependency injection:
var db = new DocumentDB(connectString, dbName: "shop");
var repo = db.GetRepo<Order>("Orders", "customerId");
await repo.Init();
Repos are registered as singletons. Always go through IDocumentDB rather than creating your own CosmosClient.
Partition keys
GetRepo<T>(container, params string[] partitionKey) takes one path for a simple key or several for a hierarchical key. Every operation has a string overload for the first case and a string[] overload for the second:
_repo = db.GetRepo<Order>("Orders", "tenantId", "customerId");
await _repo.GetItem(new[] { tenantId, customerId }, id);
Pass null as the partition key to query across partitions. That is a fan-out query: use it deliberately.
DocumentRepo<T> API
| Method | Use for |
|---|---|
GetItem / ReadItem |
Point read by partition key and id. Returns null when not found. The cheapest operation – prefer it whenever you know the id. |
AddItem |
Insert; fails when the id exists. |
UpsertItem |
Insert or replace. The optional status callback reports created versus replaced. |
PatchItem |
Partial update with a list of PatchOperation. |
DeleteItem |
Delete. Returns false when not found. |
Query(pk, linq, continuationToken?, maxItemCount?) |
LINQ query with paging. Returns QueryResult<T> (Data, TotalCount, ContinuationToken). |
Query(pk, sql, continuationToken?, maxItemCount?, parameters?) |
Parameterised SQL query with paging. |
Filter(pk, DocumentFilter<T>) |
Paged query driven by a filter object (Search, Take, ContinuationToken, overridable Build). Handy for list endpoints. |
Read(pk, linq, onRead) / ReadSQL(pk, sql, onRead) |
Process results one by one through a callback; return false from the callback to stop. |
GetItems(pk) |
All documents of a partition as IAsyncEnumerable<T>. |
ExecSQL<M>(pk, sql, ...) |
SQL projected into another type, as IAsyncEnumerable<M>. |
RawSQL / StreamSQL |
Results as JsonElement or as raw streams, for dynamic shapes and exports. |
CountSQL(pk, where) |
SELECT COUNT(1) with an optional where clause. |
CreateQuery(pk?, maxItemCount?) |
A raw IQueryable<T> to build on; run it with GetQueryResults. |
BulkInsert / BulkUpdate / BulkDelete |
Bulk operations over IEnumerable<T> or IAsyncEnumerable<T>. Tune with BulkMaxConcurrency, observe failures with OnBulkError. |
GetChangeFeedProcessor / GetAllChangesFeedProcessor |
A change feed processor for the container (lease container defaults to changeLeases). |
Exists() |
Whether the container exists. |
GetThroughputStats() / WaitForCapacity() |
RU pressure monitoring, see below. |
Continuation tokens returned by Query and Filter are opaque strings: pass them back unchanged for the next page. Always use @param placeholders with the parameters dictionary instead of concatenating values into SQL.
Throughput
By default Init() creates the database and container without explicit throughput. Set autoscale limits on the repo before it is initialised:
_repo = db.GetRepo<Order>("Orders", "customerId");
_repo.ContainerAutoscaleThroughput = 4000; // autoscale max RU/s
Point operations are retried on 429 TooManyRequests and 408 RequestTimeout, honouring the server's retry-after.
For RU-heavy loops, pause before you get throttled instead of retrying afterwards:
foreach (var order in orders) {
await _repo.WaitForCapacity(); // waits while usage is above 80% of provisioned RU/s
await _repo.UpsertItem(order.CustomerId, order);
}
GetThroughputStats() returns the observed RU/s, the provisioned RU/s, their ratio and the number of recent 429s over a rolling window. The numbers only cover requests made through that repo instance in the current process.
Diagnostics
_repo.OnDiagnostics = diag => {
logger.LogInformation("{Method} {Ms} ms, {RU} RU", diag.Method, diag.ElapsedTime?.TotalMilliseconds, diag.TotalRequestCharge);
return Task.CompletedTask;
};
Errors
Failures surface as DocumentException (with a StatusCode). DocumentContainerNotFoundException means the container was used before Init() ran. A missing document is not an error: reads return null and deletes return false.
Serialisation
Documents are serialised with System.Text.Json using JsonHelper.Options from Corner49.Infra.Core: camelCase property names, enums as strings, nulls omitted. Use [JsonPropertyName] only where the stored name must differ, and make sure your document exposes id.
Related packages
- Corner49.Infra – web apps and APIs
- Corner49.Infra.CLI – console apps and jobs
- Corner49.Infra.Core – abstractions and utilities
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- Corner49.Infra.Core (>= 10.0.169)
- Microsoft.Azure.Cosmos (>= 3.63.2)
- Newtonsoft.Json (>= 13.0.4)
- OpenTelemetry (>= 1.15.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 10.0.169 | 38 | 10/21/2026 |
| 10.0.168 | 40 | 10/21/2026 |
| 10.0.167 | 39 | 10/21/2026 |
| 10.0.166 | 59 | 10/20/2026 |
| 10.0.165 | 46 | 10/20/2026 |
| 10.0.164 | 41 | 10/20/2026 |
| 10.0.163 | 37 | 10/20/2026 |
| 10.0.162 | 48 | 10/20/2026 |
| 10.0.161 | 40 | 10/20/2026 |
| 10.0.159 | 45 | 10/20/2026 |
| 10.0.158 | 71 | 10/19/2026 |
| 10.0.157 | 77 | 10/19/2026 |
| 10.0.156 | 126 | 10/16/2026 |
| 10.0.154 | 135 | 10/14/2026 |
| 10.0.153 | 112 | 10/14/2026 |
| 10.0.151 | 248 | 10/8/2026 |
| 10.0.150 | 100 | 10/8/2026 |
| 10.0.149 | 102 | 10/8/2026 |
| 10.0.148 | 101 | 10/8/2026 |
| 10.0.147 | 105 | 10/8/2026 |