Uniphar.Cosmos.Extensions
7.0.0
dotnet add package Uniphar.Cosmos.Extensions --version 7.0.0
NuGet\Install-Package Uniphar.Cosmos.Extensions -Version 7.0.0
<PackageReference Include="Uniphar.Cosmos.Extensions" Version="7.0.0" />
<PackageVersion Include="Uniphar.Cosmos.Extensions" Version="7.0.0" />
<PackageReference Include="Uniphar.Cosmos.Extensions" />
paket add Uniphar.Cosmos.Extensions --version 7.0.0
#r "nuget: Uniphar.Cosmos.Extensions, 7.0.0"
#:package Uniphar.Cosmos.Extensions@7.0.0
#addin nuget:?package=Uniphar.Cosmos.Extensions&version=7.0.0
#tool nuget:?package=Uniphar.Cosmos.Extensions&version=7.0.0
cosmos-extensions
NuGet package repository for Cosmos Extensions
Purpose
This library is intended for provisioning Az Cosmos Database(s) and container(s).
It also updates TTL and indexing policy for existing containers.
Integration tests
The integration tests read KeyVault:Uri (the vault name) and
KeyVault:CosmosConnectionStringSecretName from
src/Uniphar.Cosmos.Extensions.IntegrationTests/appsettings.json. Authenticate
with a credential supported by DefaultAzureCredential that can read the secret.
The secret must contain a Cosmos DB connection string with permissions to create
and delete databases. Run these tests only against a dedicated test account: they
create temporary databases and attempt to delete them afterwards.
Before running the integration tests locally, make sure you have a valid Azure sign-in session. The tests fetch the Cosmos connection string from Key Vault using
DefaultAzureCredential, so an expired or MFA-challenged session causes everyCosmosExtensionsTeststest to fail in the fixture withAzure.Identity.CredentialUnavailableException/AADSTS50078— before any test logic runs. Sign in with the following and then rerun the tests:# Azure CLI az login --tenant "<tenant-id>"
Setup your project to use Cosmos Extension package
When using this NuGet package you need to setup a few things in your project
appsettings.json
Add this to structure to your appsettings.json with the appropriate values needed in your solution.
Note that this contains examples from PIMS API. They are here to illustrate example values.
"StoreOptions": {
"DatabaseName": "pims-api",
"DatabaseThroughput": <provisioned database throughput in RUs>,
"Containers": [
{
"InstanceName": "responsePayloadContainer",
"PartitionKey": "/partition",
"DefaultTimeToLive": "128.0:0:0.0"
},
{
"InstanceName": "auditContainer",
"PartitionKey": "/partition",
"IncludedPaths": [
{
"Path": "/myProperty/*"
}
]
"ExcludedPaths": [
{
"Path": "/*"
}
]
},
{
"InstanceName": "sequenceContainer",
"PartitionKey": "/id",
"IndexingMode": "None"
},
//...more containers to be defined with potential settings
{
"InstanceName": "<name of container>",
"PartitionKey": "<name of partition key>",
"ContainerThroughput": <provisioned database throughput in RUs>,
"DefaultTimeToLive" :"128.0:0:0.0"
"IndexingMode": "<indexing mode value>"
"CompositeIndexes": [
{
"Paths": [
{
"Path": "/path1",
"Order": "Ascending"
},
{
"Path": "/path2",
"Order": "Ascending"
}
]
}
]
}
]
}
NOTE 1: The
PartitionKeyPath(unless it is also "/id") is not indexed and should be included in the index.
NOTE 2: The
PartitionKeyshould always be specified in the request options object in Linux/MacOS clients
NOTE 3: Worth noting on the settings.
DatabaseName: Name of the database to be checked/created. Mandatory.DatabaseThroughput: integer, if undefined (null) it will default to 400; it will provision database with auto scaling as Manual throughput has been dismissed.Containers:InstanceName: string, name of container. Mandatory.Containers:PartitionKey: string, if undefined (null), it will default to partitioning by/partitionBe aware that partitionKey in appsettings will need to define a name preceded with a forwards slashContainers:ContainerThroughput: integer, if undefined (null) it will default to 400DefaultTimeToLiveAsTimeSpan: Optional TimeSpan defining for how long data should be retained; if undefined (null) we implement it to default to -1 (items don’t expire by default). The example shows TTL defined as 128 days, zero days, zero minutes and zero secondsIndexingMode: Optional If undefined (null), it will default toIndexingMode.Consistent. If required, then use one of these enumerated values (with capitalization!!!):None,Lazy,Consistent.CompositeIndexes: Optional The set of composite indexes to add to the parent container.
Range Indexes
https://learn.microsoft.com/en-us/azure/cosmos-db/index-policy
TLDR;
/*must be inIncludedPathsorExcludedPathsto enable range indexes.- The path must end with
?,[], or*to enable range indexes.?- Single value[]- Array. Numbers are also supported to index a specific array element.my-array/1/my-property/?*- Anything
Composite Indexes
| Property | Description |
|---|---|
| Path | The full path in a document used for composite indexing |
| Order | The sort order for the composite path. Can be ascending or descending |
See here for more details about composite indexes.
Program.cs
Add the following to Program.cs
- Add this to bind the above configuration section to class
StoreOptions. That will ensure we can DI it into the where ever we need to make the call.
builder.Services.Configure<StoreOptions>(
builder.Configuration.GetSection(nameof(StoreOptions)));
- Register a singleton instance of a
CosmosExtension
builder.Services.AddSingleton<CosmosExtension>();
- Register
CosmosClient(MS recommends a singleton) withAddCosmos. Pass the Cosmos connection string (AccountEndpoint=...;AccountKey=...), typically read from the Key Vault secret viaIConfiguration(see Cosmos Repository):
// System.Text.Json with JsonStringEnumConverter
var cosmosClientOptions = new CosmosClientOptions().DefaultOptions();
// Register the client
var cosmosSecretName = $"uni-dawn-{builder.Environment.EnvironmentName}-cosmos-connection-string";
var cosmosConnectionString = builder.Configuration[cosmosSecretName]!;
var databaseId = builder.Configuration["StoreOptions:DatabaseName"]!;
builder.AddCosmos(cosmosConnectionString, databaseId, cosmosClientOptions);
NOTE: The Cosmos connection string is stored in Key Vault as
uni-dawn-{environment}-cosmos-connection-string(for example,uni-dawn-dev-cosmos-connection-string) with the valueAccountEndpoint=https://...documents.azure.com:443/;AccountKey=.... Register the Key Vault configuration provider with aReloadIntervalso rotated keys are picked up without a restart:builder.Configuration.AddAzureKeyVault(new Uri(kvUri), tokenCredential, new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(builder.Configuration.GetValue<int>("KeyVaultReloadIntervalMinutes")) });
CosmosInitialiser.cs (or other file responsible of Cosmos Initialization)
Whatever file responsible for initializing cosmos database and containers (called from StartupBackgroundService.cs) has a method ExecuteAsync(CancellationToken stoppingToken).
That method can be simplified to this
public async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Creating Cosmos Database And Containers");
await _cosmosExtension.ExecuteAsync(stoppingToken);
}
Create extended class of StoreOptions
Some APIs may have additional logic that is specific to the solutions. You can then create a class extension that inherits from StoreOptions.
This is particular valid for PIMS API. You would create something like this.
public class ExtendedStoreOptions : StoreOptions
{
/// <summary>
/// Disable the account processing check
/// </summary>
/// <remarks>
/// If set to true all account processing checks will return true
/// Used to disable routing of requests to legacy pims system
/// </remarks>
public bool DisableAccountCheck { get; set; } = false;
}
Your appsettings.json would look like this then (based on PIMS API as an example)
"ExtendedStoreOptions": {
"DatabaseName": "<name of database>",
"DatabaseThroughput": <provisioned database throughput in RUs>,
"DisableAccountCheck": true, // < --- this is the extra field from the above example
"Containers": [
{
"InstanceName": "<name of container>",
"PartitionKey": "<name of partition key>",
"ContainerThroughput": <provisioned database throughput in RUs>,
"DefaultTimeToLiveInSeconds" : "128.0:0:0.0"
},
//...more containers to be defined
]
}
Your program.cs would then need to bind the config section like this
builder.Services.Configure<ExtendedStoreOptions>(
builder.Configuration.GetSection(nameof(ExtendedStoreOptions)));
Likewise you;ll need to update Store.cs to reflect using ExtendedStoreOptions instead.
Cosmos Repository
ICosmosRepository<T> is a wrapper around Container which handles exception handling, telemetry, and utility methods.
Also, there is no need to specify the type anymore on each method.
The below code registers CosmosClient, and ICosmosRepository<T> as singletons:
// Program.cs
var cosmosClientOptions = new CosmosClientOptions().DefaultOptions();
var cosmosSecretName = $"uni-dawn-{builder.Environment.EnvironmentName}-cosmos-connection-string";
var databaseId = builder.Configuration["StoreOptions:DatabaseName"]!;
var containerSuffix = builder.Configuration["StoreOptions:Suffix"];
builder.AddCosmos(cosmosConnectionString, databaseId, cosmosClientOptions, containersSuffix: containerSuffix)
.AddRepository<EntityType1>("myEntityContainer1")
.AddRepository<EntityType2>("myEntityContainer2")
Account key rotation
Why a connection string alone is not enough
A
CosmosClientconstructed from a connection string (new CosmosClient(connectionString, options)) copies the account key at construction time and can never be rotated — the only way to pick up a new key is to dispose the client and create a new one. The only rotatable input the SDK accepts is anAzureKeyCredential: callingAzureKeyCredential.Update(newKey)changes the key used by the existing client for all subsequent requests.That is why
CosmosCredentialProviderparsesAccountEndpointandAccountKeyout of the secret itself and builds the client asnew CosmosClient(endpoint, azureKeyCredential, options)instead of passing the connection string straight through. Never bypass this by constructing aCosmosClientfrom the raw connection string if you need rotation.
AddCosmos takes the Cosmos connection string and wires up the rotation-capable client for you:
- Binds a named
CosmosConnectionOptions(name = the connection string) holding the value (e.g.AccountEndpoint=https://uni-dawn-dev-cosmos.documents.azure.com:443/;AccountKey=...). - Registers a configuration change token for that name so
IOptionsMonitor.OnChangefires when configuration reloads. - Registers
CosmosCredentialProvideras a keyed singleton (key = the connection string); it parsesAccountEndpointandAccountKeyand holds a singleAzureKeyCredential. - Registers
CosmosClientasnew CosmosClient(provider.Endpoint, provider.Credential, clientOptions)— the endpoint is derived from the connection string and the key is updated in place on the existing client viaAzureKeyCredential.Update.
Note:
AddCosmosreceives the connection string value, not the configuration key it came from. On a Key Vault reload the named option is re-populated with that same captured value, so a rotated key is only applied to the live client when the namedCosmosConnectionOptionsis fed from a reloadable source (seeReloadableCosmosClientTests.ReloadUpdatesCredentialOnExistingClientfor the wiring). With the plainAddCosmoscall a rotated secret is picked up on the next application restart.
When CosmosCredentialProvider observes a new key, it is applied with no restart and no new client or
repositories. Keep the previous key valid for longer than KeyVaultReloadIntervalMinutes so every instance
has picked up the new one. An empty or unparsable value is logged and ignored, leaving the last good key in
place. Changing the account endpoint logs a warning and requires a restart.
CosmosClient is also available as a keyed service (GetRequiredKeyedService<CosmosClient>(connectionString)),
so several AddCosmos calls with different connection strings keep independent clients and repositories.
Secrets are never written to logs or exceptions
The connection string contains the Cosmos account key, which is a secret. Writing it to logs, telemetry or exception messages would surface it in Application Insights, log sinks and crash dumps and is a finding in penetration and security testing. The library therefore never writes the raw connection string or account key anywhere it can be observed:
CosmosCredentialProvider.Redact(connectionString)replaces theAccountKeyvalue with[REDACTED](e.g.AccountEndpoint=https://...documents.azure.com:443/;AccountKey=[REDACTED]). AllArgumentExceptionmessages andLogWarningcalls in the provider use this redacted form only.- Redaction is a pure string transformation for diagnostics. It does not affect authentication: the real key
is still parsed and applied to the
AzureKeyCredential, including on rotation.
| Use | Value used |
|---|---|
options.Get(name) / OnChange name matching |
raw service key (the connection string) |
Parse(...) → (endpoint, key) |
raw connection-string value from the option |
new AzureKeyCredential(key) |
real initial AccountKey |
Credential.Update(newKey) on reload |
real rotated AccountKey |
Endpoint |
real account endpoint |
ArgumentException messages, LogWarning messages |
Redact(connectionString) → AccountKey=[REDACTED] |
When extending the library or writing calling code, follow the same rule: never log, trace or include in an
exception a connection string, AccountKey, AzureKeyCredential.Key or any other value that may be a secret.
Use CosmosCredentialProvider.Redact (or log only the endpoint / secret name) instead.
TTelemetryhas to extendIBaseTelemetry.
To use, just inject ICosmosRepository<T> into your class:
public class MyService(
ICosmosRepository<MyEntity> entityRepository)
{
}
Handled exception status codes
When the following exceptions are thrown, the methods returns null.
| Methods | Status Code |
|---|---|
CreateItemAsync |
Conflict |
ReadItemAsync |
NotFound |
ReplaceItemAsync |
NotFound |
PatchItemAsync* |
NotFound |
DeleteItemAsync |
NotFound |
*
PatchItemAsyncreturns an empty list if not found.
Queries
There are a couple of helper methods to enumerate Cosmos queries from FeedIterator<T>:
ToListAsync(cancellationToken)ToAsyncEnumerable(cancellationToken)FirstOrDefaultAsync(cancellationToken)
Testing
When mocking queries, use the following methods to generate the response:
IEnumerable<T>.ToMockRepositoryQueryable()IEnumerable<T>.ToMockRepositoryFeedIterator()
Telemetry
Each method sends a CosmosDbMetrics that logs RU usage and other metrics.
It is possible to disable telemetry at:
- Globally: in
AddCosmos. - Repository level: in
AddRepository. - In each method.
Keyed Repository
If two or more repositories use the same object type, it is possible to use a keyed repository.
// Program.cs
.AddRepository<Entity>("rightEntity", serviceKey: "right")
.AddRepository<Entity>("leftEntity", serviceKey: "left")
// Service.cs
[FromKeyedServices("right")] ICosmosRepository<Entity> rightRepository,
Cosmos Exception Handler
There is a global exception handler to log CosmosException methods. It is registered automatically with AddCosmos.
To register it manually:
builder.Services.AddSingleton<IExceptionHandler, CosmosExceptionHandler>(provider =>
{
var telemetry = provider.GetRequiredService<ExampleServiceTelemetry>();
return new CosmosExceptionHandler(telemetry!);
});
Cosmos Mutex
The CosmosMutex class is an implementation of a simple distributed mutex. The CosmosMutex utilizes a Cosmos container as a backing durable store for a give mutex state.
Initialization
An instance of a CosmosMutex must be initialized before it can be used by an application. This initialization can be performed during startup.
To initialize a CosmosMutex invoke the InitializeAsync during the startup initialization of the application.
The InitializeAsync method requires the following parameters:
- mutexInstance
- The name of the mutex that is being acquired
public override async Task StartAsync(CancellationToken cancellationToken)
{
_logger!.LogInformation("Creating Cosmos Database And Containers");
// Supply the mutex instance name to the initialize method
await _mutex.InitializeAsync(MutexName);
_logger!.LogInformation("Health Check Startup Completed");
_healthCheck!.StartupCompleted = true;
}
Acquire
In order to access some distributed data in an exclusive access context a named CosmosMutex must be acquired by a process.
The AcquireAsync method requires the following parameters:
- Owner
- The Owner name of the process attempting to acquire the mutex instance
- mutexInstance
- The name of the mutex that is being acquired
- leasExpiry
- The maximum length of time the mutex can be held. An application must allow for enough time to complete its exclusive processing
Note: The mutex is released after the leaseExpiry time has elapsed.
// Attempt to acquire the mutex supplying the machine name as the acquiring owner of the mutex
if (await _mutex.AcquireAsync(Environment.MachineName, MutexName, _mutexLeaseTime))
{
// Perform execution in a mutually exclusive context
await ProcessAsync(cancellationToken);
// Release the mutex
await _mutex.ReleaseAsync(Environment.MachineName, MutexName, cancellationToken);
}
Release
After a process has completed executing its mutually exclusive operation an acquired CosmosMutex must be released.
The ReleaseAsync method requires the following parameters:
- owner
- The Owner name of the process attempting to acquire the mutex instance
- mutexInstance
- The name of the mutex that is being acquired
{
// Release the mutex
await _mutex.ReleaseAsync(Environment.MachineName, MutexName, cancellationToken);
}
| 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
- Microsoft.Azure.Cosmos (>= 3.64.0)
- Newtonsoft.Json (>= 13.0.4)
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 | |
|---|---|---|---|
| 7.0.0 | 0 | 11/26/2026 | |
| 6.0.0 | 54 | 11/24/2026 | |
| 5.0.3 | 576 | 11/12/2026 | |
| 5.0.2 | 5,024 | 7/15/2026 | |
| 5.0.1 | 733 | 6/16/2026 | |
| 5.0.0 | 124 | 6/9/2026 | |
| 4.15.0 | 11,094 | 9/11/2025 | |
| 4.14.0 | 1,020 | 8/28/2025 | |
| 4.13.1 | 1,040 | 7/30/2025 | |
| 4.13.0 | 265 | 7/28/2025 | |
| 4.12.0 | 670 | 7/23/2025 | |
| 4.11.0 | 1,045 | 7/2/2025 | |
| 4.10.0 | 1,348 | 4/23/2025 | |
| 4.9.0 | 501 | 4/17/2025 | |
| 4.8.0 | 327 | 4/17/2025 | |
| 4.7.0 | 492 | 4/15/2025 | |
| 4.6.0 | 390 | 4/11/2025 | |
| 4.5.0 | 287 | 4/11/2025 | |
| 4.4.1 | 423 | 4/9/2025 | |
| 4.4.0 | 353 | 4/9/2025 |