in src/CosmosCache.cs [490:547]
private async Task<Container> CosmosContainerInitializeAsync()
{
this.initializedClient = this.options.CosmosClient == null;
this.cosmosClient = this.GetClientInstance();
if (this.options.CreateIfNotExists)
{
DatabaseResponse databaseResponse = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(this.options.DatabaseName).ConfigureAwait(false);
this.options.DiagnosticsHandler?.Invoke(databaseResponse.Diagnostics);
int defaultTimeToLive = this.options.DefaultTimeToLiveInMs.HasValue
&& this.options.DefaultTimeToLiveInMs.Value > 0 ? (int)TimeSpan.FromMilliseconds(this.options.DefaultTimeToLiveInMs.Value).TotalSeconds : CosmosCache.DefaultTimeToLive;
try
{
ContainerResponse existingContainer = await this.cosmosClient.GetContainer(this.options.DatabaseName, this.options.ContainerName).ReadContainerAsync().ConfigureAwait(false);
this.options.DiagnosticsHandler?.Invoke(existingContainer.Diagnostics);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
this.options.DiagnosticsHandler?.Invoke(ex.Diagnostics);
// Container is optimized as Key-Value store excluding all properties
string partitionKeyDefinition = CosmosCache.ContainerPartitionKeyPath;
if (!string.IsNullOrWhiteSpace(this.options.ContainerPartitionKeyAttribute))
{
partitionKeyDefinition = $"/{this.options.ContainerPartitionKeyAttribute}";
}
ContainerResponse newContainer = await this.cosmosClient.GetDatabase(this.options.DatabaseName).DefineContainer(this.options.ContainerName, partitionKeyDefinition)
.WithDefaultTimeToLive(defaultTimeToLive)
.WithIndexingPolicy()
.WithIndexingMode(IndexingMode.Consistent)
.WithIncludedPaths()
.Attach()
.WithExcludedPaths()
.Path("/*")
.Attach()
.Attach()
.CreateAsync(this.options.ContainerThroughput).ConfigureAwait(false);
this.options.DiagnosticsHandler?.Invoke(newContainer.Diagnostics);
}
}
else
{
try
{
ContainerResponse existingContainer = await this.cosmosClient.GetContainer(this.options.DatabaseName, this.options.ContainerName).ReadContainerAsync().ConfigureAwait(false);
this.options.DiagnosticsHandler?.Invoke(existingContainer.Diagnostics);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
this.options.DiagnosticsHandler?.Invoke(ex.Diagnostics);
throw new InvalidOperationException($"Cannot find an existing container named {this.options.ContainerName} within database {this.options.DatabaseName}");
}
}
return this.cosmosClient.GetContainer(this.options.DatabaseName, this.options.ContainerName);
}