Skip to content

Instantly share code, notes, and snippets.

@mykeels

mykeels/MyDbContext.cs Secret

Created Sep 29, 2019
Embed
What would you like to do?
An impl. of Audit in a DbContext
public class MyDbContext : DbContext
{
private readonly IServiceProvider _serviceProvider;
public DbSet<Company> Companies { get; set; }
public MyDbContext(DbContextOptions<MyDbContext> options, IServiceProvider provider) : base(options)
{
_serviceProvider = provider;
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.FilterSoftDeletedEntries<Company>();
}
public override int SaveChanges()
{
var user = GetCurrentUserInfo().Result;
this.EnsureAudit<Guid?>(user?.Id);
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var user = GetCurrentUserInfo().Result;
this.EnsureAudit<Guid?>(user?.Id);
return base.SaveChangesAsync(cancellationToken);
}
private async Task<ApplicationUser> GetCurrentUserInfo()
{
var _httpContextAccessor = _serviceProvider.GetService<IHttpContextAccessor>();
var userManager = _serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
ApplicationUser user = null;
if (_httpContextAccessor.HttpContext?.User != null)
{
var claimsPrincipal = _httpContextAccessor.HttpContext?.User;
user = await userManager.GetUserAsync(claimsPrincipal);
}
return user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment