Skip to content

Instantly share code, notes, and snippets.

@JeremyLikness
Created May 14, 2020 04:29
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 JeremyLikness/b73ec9f54983a4d4e204faafd06511ee to your computer and use it in GitHub Desktop.
Save JeremyLikness/b73ec9f54983a4d4e204faafd06511ee to your computer and use it in GitHub Desktop.
A blog client that retries credentials
using BlazorCosmosWasm.Shared;
using Microsoft.EntityFrameworkCore;
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace BlazorCosmosWasm.Client.Data
{
public class BlogClient : IBlogClient
{
private CosmosCredentials Credentials;
private readonly HttpClient Http;
public BlogClient(HttpClient client)
{
Http = client;
}
public async Task<BlogContext> GetDbContextAsync()
{
if (Credentials == null)
{
await GetCredentialsAsync();
}
BlogContext context = null;
CosmosCredentials getCredentials() => Credentials;
var options = new DbContextOptionsBuilder<BlogContext>()
.UseCosmos(getCredentials().EndPoint, getCredentials().Key, BlogContext.DatabaseName,
opt =>
opt.ConnectionMode(Microsoft.Azure.Cosmos.ConnectionMode.Gateway));
try
{
context = new BlogContext(options.Options);
}
catch
{
// try again with fresh credentials
await GetCredentialsAsync();
context = new BlogContext(options.Options);
}
return context;
}
private async Task GetCredentialsAsync()
{
Credentials = await Http.GetFromJsonAsync<CosmosCredentials>("api/Cosmos");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment