-
-
Save mykeels/ab22da3a756b6408d6d8cbaea374116a to your computer and use it in GitHub Desktop.
An impl. of Audit in a DbContext
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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