I have an ApplicationDbContext class : ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> where I have override methods on SaveChanges && SaveChangesAsync to include the UpdateAuditEntities method. What i want is to get the user-name / email of the logged in user so every entity that inherits from IAuditableEntity is tagged with the user who created / updated the entity.
private void UpdateAuditEntities() { var CurrentUserId = ???; var modifiedEntries = ChangeTracker.Entries() .Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified)); foreach (var entry in modifiedEntries) { var entity = (IAuditableEntity)entry.Entity; DateTime now = DateTime.UtcNow; if (entry.State == EntityState.Added) { entity.CreatedDate = now; entity.CreatedBy = CurrentUserId; } else { base.Entry(entity).Property(x => x.CreatedBy).IsModified = false; base.Entry(entity).Property(x => x.CreatedDate).IsModified = false; } entity.UpdatedDate = now; entity.UpdatedBy = CurrentUserId; } } Doing my research, i found a good article here but I have a DesignTimeDbContextFactory implementation like below:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> { public ApplicationDbContext CreateDbContext(string[] args) { Mapper.Reset(); IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddJsonFile("appsettings.Development.json", optional: true) .Build(); var builder = new DbContextOptionsBuilder<ApplicationDbContext>(); //IUserResolverService userResolverService = ServiceProviderServiceExtensions.CreateScope() builder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"], b => b.MigrationsAssembly("SybrinApp.Pro")); return new ApplicationDbContext(builder.Options); } } The suggested solution means my ApplicationDbContext will need UserResolverService to instantiate. How can i go about injecting UserResolverService into the DesignTimeDbContextFactory implementation or is there another way to get the currently logged in user in my class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
public override int SaveChanges() { UpdateAuditEntities(); return base.SaveChanges(); }theUpdateAuditEntitiesmethod is the one posted in the question. So this is in the ApplicationDbContext class which is am implementation ofIdentityDbContext