0

I am trying to access logged in user id in Persistence layer. I am using Claim and want to capture centralize created by and created on, logic below is my code kindly suggest me best approach

public class DBContext : DbContext
{
   public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
    {
        var AddedEntities = ChangeTracker.Entries().Where(E => E.State == EntityState.Added).ToList();
        AddedEntities.ForEach(E =>
        {
            var prop = E.Metadata.FindProperty("CreatedOn");
            if (prop != null)
            {
                E.Property("CreatedOn").CurrentValue = DateTimeHelper.DateTimeNow;
              // This is a Persistence layer and want here to get logged in user Id 
              //  E.Property("CreatedBy").CurrentValue=loggedInUserIdfromClaim
            }
        });
        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }
}
  • 2
    Id suggest not do this at all IMO. This should be a concern of (and in the contract) passed down to your datalayer not of the layer itself, otherwise you would need to make authorization a crosscutting concern, which seems problematic – TheGeneral Apr 07 '21 at 05:44
  • Actually what you want to access is kind of ***ambient info***. So up to a point, it's acceptable. But it depends on how you setup that ambient info. Here you should not consume the `HttpContext` directly. You need to abstract it. – King King Apr 07 '21 at 07:45
  • Thanks for comments, Actually I do not want to pass every time user id from UI layer to service layer on every action. Is any good approach? Which not violet the SOLID principle and I can achieve it with Centralized approach. – user15570838 Apr 08 '21 at 08:11

0 Answers0