Search documentationEsc

ServiceProviderExtensions

Extension methods for `IServiceProvider` to support Cosmos Repository operations.

Namespace: Microsoft.Azure.CosmosRepository.AspNetCore.Extensions
Kind: class

Extension methods for IServiceProvider to support Cosmos Repository operations.

public static class ServiceProviderExtensions

Example

Members

Method

ServiceProviderExtensions.EagerlyInitializeCosmosContainersAsync(IServiceProvider, params Assembly[]?)

Eagerly initializes Cosmos DB database and containers before the application starts handling requests.

public static Task<IServiceProvider> EagerlyInitializeCosmosContainersAsync(this IServiceProvider serviceProvider, params Assembly[]? assemblies)

Parameters

NameTypeDescription
serviceProviderIServiceProviderThe service provider.
assembliesAssembly[]The assemblies to scan for IItem types. Optional. If not provided and no types are explicitly configured, types are discovered from all loaded assemblies.

ReturnsIServiceProvider}: The service provider for method chaining.

This method triggers the creation of the Cosmos DB database and containers that would normally be created lazily on first access when IsAutoResourceCreationIfNotExistsEnabled is enabled.

The method discovers item types in two ways:

Types explicitly configured via ContainerBuilder.Configure()Types discovered by scanning assemblies (when assemblies parameter is provided or no types are explicitly configured)

Use this method to:

Ensure containers exist before health checks run (prevents health check failures during lazy initialization)Avoid latency on the first request to your applicationFail fast during startup if there are Cosmos DB configuration or connectivity issues

Important: If IsAutoResourceCreationIfNotExistsEnabled is false, this method does nothing and returns immediately. The database and containers must already exist in that case.

Timing: Call this method after Build() but before Run() in your application startup code. Containers will still be created on first use when auto-creation is enabled even if this method is not called - this just moves the timing from first-access to startup.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCosmosRepository(options =>
{
options.ContainerBuilder.Configure<Product>(c => c.WithContainer("products"));
});
builder.Services.AddHealthChecks().AddCosmosRepository();
var app = builder.Build();
// Eagerly initialize containers before starting the application
// Will discover Product from explicit configuration
await app.Services.EagerlyInitializeCosmosContainersAsync();
app.MapHealthChecks("/health");
app.Run();