Skip to content

API Reference

Aryeh Citron edited this page Apr 20, 2026 · 26 revisions

Complete reference for all public classes and methods in the CosmosDB.InMemoryEmulator packages.

See also: Getting Started · Choosing Your Approach · Setup Guide · SQL Queries · Known Limitations

Package: CosmosDB.InMemoryEmulator

InMemoryCosmos (Static)

Entry point for creating in-memory Cosmos DB test infrastructure. New in 3.0.0.

Member Type Description
DefaultDatabaseName string "default" — default database for AddContainer()
Method Returns Description
Create(containerName, partitionKeyPath, ...) InMemoryCosmosResult Single-container setup (one-liner)
Create(containerName, partitionKeyPaths, ...) InMemoryCosmosResult Single-container with hierarchical PK
Builder() InMemoryCosmosBuilder Multi-container/advanced builder

InMemoryCosmosBuilder

Method Returns Description
AddContainer(name, pkPath, configure?) InMemoryCosmosBuilder Add container to default database
AddContainer(name, pkPaths, configure?) InMemoryCosmosBuilder Add container with hierarchical PK
AddDatabase(dbName, configure) InMemoryCosmosBuilder Add a named database with containers
WrapHandler(wrapper) InMemoryCosmosBuilder Add HTTP handler wrapper
ConfigureOptions(configure) InMemoryCosmosBuilder Configure CosmosClientOptions
Build() InMemoryCosmosResult Build the setup

InMemoryCosmosResult : IDisposable, IAsyncDisposable

Member Type Description
Client CosmosClient The in-memory-backed CosmosClient
Container Container SDK Container (single-container only)
Containers IReadOnlyDictionary<string, Container> All SDK Containers by name
Handler FakeCosmosHandler Handler (single-container only)
Handlers IReadOnlyDictionary<string, FakeCosmosHandler> All handlers by name
Method Returns Description
SetupContainer(name?) IContainerTestSetup Test setup for a container (registration)
GetHandler(name) FakeCosmosHandler Handler for a named container
SetFaultInjector(injector) void Set/clear fault injector on all handlers
Database(dbName) InMemoryDatabaseResult Database-scoped access
Databases IReadOnlyDictionary<string, InMemoryDatabaseResult> All databases
ExportState(name?) string Export container state as JSON
ExportStateToFile(path, name?) void Export container state to a file
ImportState(json, name?) void Import container state from JSON
ImportStateFromFile(filePath, name?) void Import container state from a file
RestoreToPointInTime(timestamp, name?) void Restore container to a point in time
ClearItems(name?) void Remove all items from the container

InMemoryDatabaseResult

Member Type Description
DatabaseName string The database name
Containers IReadOnlyDictionary<string, Container> Containers in this database
Handlers IReadOnlyDictionary<string, FakeCosmosHandler> Handlers in this database
Method Returns Description
SetupContainer(name) IContainerTestSetup Test setup for a container in this database
GetHandler(name) FakeCosmosHandler Handler for a container in this database
SetFaultInjector(injector) void Set/clear fault injector on this database's handlers
ExportState(name) string Export container state as JSON
ExportStateToFile(name, path) void Export container state to a file
ImportState(name, json) void Import container state from JSON
ImportStateFromFile(name, filePath) void Import container state from a file
RestoreToPointInTime(name, timestamp) void Restore container to a point in time
ClearItems(name) void Remove all items from the container

IContainerTestSetup

Focused interface for test-only operations. Implemented internally by InMemoryContainer.

Property Type Description
DefaultTimeToLive int? Container-level TTL in seconds
FeedRangeCount int Number of feed ranges (default 1). Set > 1 to simulate multiple physical partitions
MaxChangeFeedSize int Maximum change feed entries retained (default 1000). Set to 0 for unbounded
StateFilePath string? Path for automatic state persistence
ItemCount int Number of items currently stored
PartitionKeyPaths IReadOnlyList<string> Partition key path(s)
JsTriggerEngine IJsTriggerEngine? JavaScript trigger engine
SprocEngine ISprocEngine? JavaScript stored procedure engine
Method Returns Description
RegisterStoredProcedure(name, handler) void Register C# stored procedure
RegisterStoredProcedure(name, jsBody) void Register JS stored procedure (requires JsTriggers package)
RegisterUdf(name, handler) void Register C# UDF
RegisterUdf(name, jsBody) void Register JS UDF (requires JsTriggers package)
RegisterTrigger(name, type, operation, handler) void Register C# trigger
RegisterTrigger(name, type, operation, jsBody) void Register JS trigger (requires JsTriggers package)
ExportState() string Export container state as JSON
ExportStateToFile(path) void Export container state to a file
ImportState(json) void Import container state from JSON
ImportStateFromFile(filePath) void Import container state from a file
RestoreToPointInTime(timestamp) void Restore container to a point in time via change feed replay
ClearItems() void Remove all items from the container

FakeCosmosHandler

HTTP message handler that intercepts Cosmos SDK requests and serves them from an in-memory container. Used internally by all integration approaches — see the Setup Guide for usage examples. Obtain via InMemoryCosmosResult.Handler or InMemoryCosmosResult.GetHandler(name).

Namespace: CosmosDB.InMemoryEmulator
Inherits: System.Net.Http.HttpMessageHandler

Note: Constructors are internal. Use InMemoryCosmos.Create() or InMemoryCosmos.Builder() to obtain handler instances.

Properties

Property Type Description
BackingContainer Container The underlying in-memory container (as SDK Container)
RequestLog IReadOnlyCollection<string> Recorded HTTP requests
QueryLog IReadOnlyCollection<string> Recorded SQL queries
FaultInjector Func<HttpRequestMessage, HttpResponseMessage?>? Fault injection delegate
FaultInjectorIncludesMetadata bool Whether faults affect metadata routes

Static Methods

Method Returns Description
VerifySdkCompatibilityAsync() Task SDK compatibility self-test

In-memory implementation of User.

Namespace: CosmosDB.InMemoryEmulator
Inherits: Microsoft.Azure.Cosmos.User
Sealed: Yes

Properties

Property Type Description
Id string User identifier

Methods

Method Returns Description
ReadAsync(...) UserResponse Read user properties
ReplaceAsync(UserProperties, ...) UserResponse Replace user properties
DeleteAsync(...) UserResponse Delete user
GetPermission(string id) Permission Get permission by id
CreatePermissionAsync(PermissionProperties, int?, ...) PermissionResponse Create permission (409 if exists)
UpsertPermissionAsync(PermissionProperties, int?, ...) PermissionResponse Create or replace permission
GetPermissionQueryIterator<T>(string?, string?, QueryRequestOptions?) FeedIterator<T> List permissions
GetPermissionQueryIterator<T>(QueryDefinition?, string?, QueryRequestOptions?) FeedIterator<T> List permissions by query

InMemoryPermission

In-memory implementation of Permission.

Namespace: CosmosDB.InMemoryEmulator
Inherits: Microsoft.Azure.Cosmos.Permission
Sealed: Yes

Properties

Property Type Description
Id string Permission identifier

Methods

Method Returns Description
ReadAsync(int?, ...) PermissionResponse Read permission properties
ReplaceAsync(PermissionProperties, int?, ...) PermissionResponse Replace permission properties
DeleteAsync(...) PermissionResponse Delete permission

FakeCosmosHandlerOptions

Configuration for FakeCosmosHandler.

Namespace: CosmosDB.InMemoryEmulator
Sealed: Yes

Property Type Default Description
CacheTtl TimeSpan 5 min Query result cache TTL
CacheMaxEntries int 100 Max cached query results
PartitionKeyRangeCount int 1 Number of simulated partition ranges

InMemoryFeedIterator<T>

In-memory implementation of FeedIterator<T>.

Namespace: CosmosDB.InMemoryEmulator
Inherits: Microsoft.Azure.Cosmos.FeedIterator<T>

Constructors

InMemoryFeedIterator(IReadOnlyList<T> items, int? maxItemCount = null, int initialOffset = 0)
InMemoryFeedIterator(IEnumerable<T> source, int? maxItemCount = null)
InMemoryFeedIterator(Func<IReadOnlyList<T>> factory, int? maxItemCount = null)

InMemoryTransactionalBatch

In-memory implementation of TransactionalBatch. Supports CreateItem, UpsertItem, ReplaceItem, DeleteItem, ReadItem, PatchItem, and their stream variants. All operations execute atomically via ExecuteAsync.

Namespace: CosmosDB.InMemoryEmulator
Inherits: Microsoft.Azure.Cosmos.TransactionalBatch

Note: Internal class. Obtained via Container.CreateTransactionalBatch(partitionKey).


InMemoryFeedIteratorSetup

Deprecated. All recommended approaches now use FakeCosmosHandler, which handles .ToFeedIterator() natively. See How Does ToFeedIterator() Work? for details.

Namespace: CosmosDB.InMemoryEmulator

Method Description
Register() Enable in-memory feed iterator interception (legacy)
Deregister() Disable interception, revert to SDK behaviour

IJsTriggerEngine

Interface for executing JavaScript trigger bodies. Implemented by JintTriggerEngine in the JsTriggers package, or provide a custom implementation.

Namespace: CosmosDB.InMemoryEmulator

Method Returns Description
ExecutePreTrigger(string jsBody, JObject document) JObject Execute pre-trigger, returns (possibly modified) document
ExecutePreTrigger(string jsBody, JObject document, ICollectionContext context) JObject Execute pre-trigger with collection CRUD access
ExecutePostTrigger(string jsBody, JObject document) JObject? Execute post-trigger
ExecutePostTrigger(string jsBody, JObject document, ICollectionContext context) JObject? Execute post-trigger with collection CRUD access

IJsUdfEngine

Interface for executing JavaScript UDF bodies. Implemented by JintTriggerEngine.

Namespace: CosmosDB.InMemoryEmulator

Method Returns Description
ExecuteUdf(string jsBody, object[] args) object? Execute a JavaScript UDF function body

ICollectionContext

Partition-scoped document CRUD operations for use inside JavaScript stored procedures and triggers.

Namespace: CosmosDB.InMemoryEmulator

Member Returns Description
CreateDocument(JObject document) JObject Insert a document
ReadDocument(string id) JObject Read a document by ID
QueryDocuments(string sql) IReadOnlyList<JObject> Execute SQL query within partition
ReplaceDocument(string id, JObject document) JObject Replace a document
DeleteDocument(string id) void Delete a document by ID
SelfLink string Collection self link

ServiceCollectionExtensions

DI extension methods for IServiceCollection. See the Setup Guide for usage examples.

Namespace: CosmosDB.InMemoryEmulator

Method Description
UseInMemoryCosmosDB(Action<InMemoryCosmosOptions>?) Replace CosmosClient + Container registrations using FakeCosmosHandler
UseInMemoryCosmosContainers(Action<InMemoryContainerOptions>?) Replace Container registrations only
UseInMemoryCosmosDB<TClient>(Action<InMemoryCosmosOptions>?) Replace typed CosmosClient subclass + Container registrations

InMemoryCosmosOptions

Options for UseInMemoryCosmosDB() and UseInMemoryCosmosDB<TClient>().

Namespace: CosmosDB.InMemoryEmulator

Property Type Default Description
Containers List<ContainerConfig> Empty Container configurations
DatabaseName string? "in-memory-db" Default database name
RegisterFeedIteratorSetup bool true Ignored — all DI methods now use FakeCosmosHandler which handles .ToFeedIterator() natively
OnClientCreated Action<CosmosClient>? null Post-creation callback (receives real CosmosClient backed by FakeCosmosHandler, or a Castle.Core dynamic proxy for the <TClient> overload)
OnHandlerCreated Action<string, FakeCosmosHandler>? null Per-container handler callback. Fires for all DI methods including UseInMemoryCosmosDB<TClient>()
HttpMessageHandlerWrapper Func<HttpMessageHandler, HttpMessageHandler>? null Wraps the FakeCosmosHandler/router before it's passed to HttpClientFactory. Applies to all DI methods including UseInMemoryCosmosDB<TClient>()
StatePersistenceDirectory string? null Directory for automatic state persistence. Container state is loaded on creation and saved on disposal. Files are named {DatabaseName}_{ContainerName}.json. See State Persistence
Method Returns Description
-------- --------- -------------
AddContainer(string containerName, string partitionKeyPath = "/id", string? databaseName = null) InMemoryCosmosOptions Fluent helper to add a container configuration
WithHttpMessageHandlerWrapper(Func<HttpMessageHandler, HttpMessageHandler> wrapper) InMemoryCosmosOptions Fluent helper to set HttpMessageHandlerWrapper

InMemoryContainerOptions

Options for UseInMemoryCosmosContainers().

Namespace: CosmosDB.InMemoryEmulator

Property Type Default Description
Containers List<ContainerConfig> Empty Container configurations
RegisterFeedIteratorSetup bool true Obsolete. Ignored — FakeCosmosHandler handles .ToFeedIterator() natively
OnContainerCreated Action<IContainerTestSetup>? null Per-container callback
StatePersistenceDirectory string? null Directory for automatic state persistence. Container state is loaded on creation and saved on disposal. Files are named {ContainerName}.json. See State Persistence
Method Returns Description
AddContainer(string containerName = "in-memory-container", string partitionKeyPath = "/id") InMemoryContainerOptions Fluent helper to add a container configuration

ContainerConfig

public record ContainerConfig(
    string ContainerName,
    string PartitionKeyPath = "/id",
    string? DatabaseName = null);

CosmosSqlParser

Cosmos DB SQL parser (internal details exposed for advanced use).

Namespace: CosmosDB.InMemoryEmulator

Method Returns Description
Parse(string sql) CosmosSqlQuery Parse SQL (throws on failure)
TryParse(string sql, out CosmosSqlQuery) bool Parse SQL (returns false on failure)

Package: CosmosDB.InMemoryEmulator.ProductionExtensions

Deprecated. This package is no longer needed. All recommended approaches use FakeCosmosHandler, which handles .ToFeedIterator() natively. See How Does ToFeedIterator() Work? and What's New in 4.0 for details.


Package: CosmosDB.InMemoryEmulator.JsTriggers

Optional package that provides a Jint-based JavaScript engine for executing real Cosmos DB trigger scripts in tests.

JintTriggerEngine

JavaScript trigger engine built on Jint.

Namespace: CosmosDB.InMemoryEmulator.JsTriggers
Implements: IJsTriggerEngine, IJsUdfEngine

Method Returns Description
ExecutePreTrigger(string jsBody, JObject document) JObject Execute pre-trigger JavaScript, returns modified document
ExecutePreTrigger(string jsBody, JObject document, ICollectionContext context) JObject Execute pre-trigger with collection CRUD access
ExecutePostTrigger(string jsBody, JObject document) JObject? Execute post-trigger JavaScript
ExecutePostTrigger(string jsBody, JObject document, ICollectionContext context) JObject? Execute post-trigger with collection CRUD access
ExecuteUdf(string jsBody, object[] args) object? Execute JavaScript UDF body

JintSprocEngine

JavaScript stored procedure engine built on Jint.

Namespace: CosmosDB.InMemoryEmulator.JsTriggers
Implements: ISprocEngine

Method Returns Description
Execute(string jsBody, PartitionKey pk, dynamic[] args) string? Execute stored procedure without collection access
Execute(string jsBody, PartitionKey pk, dynamic[] args, ICollectionContext ctx) string? Execute stored procedure with partition-scoped collection CRUD
CapturedLogs IReadOnlyList<string> Console.log output from last execution

JsTriggerExtensions

Extension method to wire up the Jint engine.

Namespace: CosmosDB.InMemoryEmulator.JsTriggers

Method Returns Description
UseJsTriggers(this IContainerTestSetup) IContainerTestSetup Sets JsTriggerEngine to a JintTriggerEngine instance

Clone this wiki locally