Skip to content

Instantly share code, notes, and snippets.

@tebeco
Created September 24, 2020 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tebeco/59d208ee46fe3f788251103fc4e4a73d to your computer and use it in GitHub Desktop.
Save tebeco/59d208ee46fe3f788251103fc4e4a73d to your computer and use it in GitHub Desktop.
Updating DocumentDB sdk
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
namespace Foo
{
public class CosmosDbDatabaseBackgroundService : BackgroundService
{
private readonly CosmosDbOptions _cosmosDbOptions;
private readonly IDocumentClient _client;
public CosmosDbDatabaseBackgroundService(IOptions<CosmosDbOptions> cosmosDbOptions, IDocumentClient client)
{
_cosmosDbOptions = cosmosDbOptions.Value;
_client = client;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = _cosmosDbOptions.Database }).ConfigureAwait(false);
var cosmosdDbCollections = _cosmosDbOptions.Collections.Split(',', ';');
foreach (var collectionName in cosmosdDbCollections)
{
var databaseUri = UriFactory.CreateDatabaseUri(_cosmosDbOptions.Database);
var documentCollection = new DocumentCollection { Id = collectionName.Trim(), DefaultTimeToLive = _cosmosDbOptions.DefaultTimeToLiveInSec };
var options = new RequestOptions { OfferThroughput = _cosmosDbOptions.ReadUnit };
await _client.CreateDocumentCollectionIfNotExistsAsync(databaseUri, documentCollection, options).ConfigureAwait(false);
}
}
}
}
namespace Foo
{
public class CosmosDbOptions
{
public string Endpoint { get; set; }
public string Authkey { get; set; }
public string Database { get; set; }
public string Collections { get; set; }
public int ReadUnit { get; set; } = 400;
public int DefaultTimeToLiveInSec { get; set; } = 60 * 60 * 24;
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.DocumentDB.Core" />
<PackageReference Include="Microsoft.Extensions.Options" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment