Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A custom identity context to intercept user adds
using BlazorCosmosWasm.Server.Controllers;
using BlazorCosmosWasm.Server.Models;
using BlazorCosmosWasm.Shared;
using IdentityServer4.EntityFramework.Options;
using Microsoft.Azure.Cosmos;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace BlazorCosmosWasm.Server.Data
{
public class ApplicationCosmosDbContext : ApplicationDbContext
{
private readonly IConfiguration _config;
private CosmosClient client;
private CosmosClient Get_client()
{
if (client == null)
{
client = _config.CreateCosmosClientFromConfig();
}
return client;
}
public ApplicationCosmosDbContext(IConfiguration config, DbContextOptions options, IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
{
_config = config;
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
var newUsers = ChangeTracker.Entries<ApplicationUser>().Where(u => u.State == EntityState.Added);
foreach(var newUser in newUsers)
{
await AddToCosmosAsync(newUser.Entity.Email);
}
var result = await base.SaveChangesAsync(cancellationToken);
return result;
}
private async Task AddToCosmosAsync(string email)
{
var db = Get_client().GetDatabase(BlogContext.DatabaseName);
await db.CreateUserAsync(email);
Debug.WriteLine($"Added {email} to Cosmos.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.