Mark Cooper
Mark Cooper

Reputation: 6884

Current user (ASP.NET Identity) information within Generic repository pattern

I have implemented generic repository pattern over an EF Core context, for example;

    public class GenericRepository<TEntity, TContext> : IGenericRepository<TEntity>
        where TEntity : EntityBase
        where TContext : DbContext
    {
        internal TContext context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(TContext context)
        {
            this.context = context;
            dbSet = context.Set<TEntity>();
        }

        public virtual TEntity GetById(long id)
        {
            return dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        { 
            entity.CreatedDate = DateTime.Now;
            dbSet.Add(entity);
        }

        //... additional methods removed for brevity
    }

All my models are using an EntityBase class that allows me to record when the record was created and by whom, for example;

    public abstract class EntityBase {
        public long Id { get; set; }
        public DateTime CreatedDate { get; set; }
        public string CreatedBy { get; set; }
        //... additional fields removed for brevity
    }

What are the different ways to access the current user within the repository, so I can add the user to the entity on creation;

        public virtual void Insert(TEntity entity)
        { 
            entity.CreatedBy = CurrentUser.Name; // TODO: get current user here?
            entity.CreatedDate = DateTime.Now;
            dbSet.Add(entity);
        }

It feels like I should be able to do this via middleware and or injection.

Upvotes: 0

Views: 477

Answers (1)

MyPv90
MyPv90

Reputation: 76

I think, you should pass user information from controller to the repository method or set CreatedBy value inside the controller instead of Repository method. Moreover , in my opinion you should avoid depend your repository to the identity and keep it simple and independent.

In other words, referencing HttpContext.User.Identity inside your repository is not a good idea,and HttpContext belog to the Presentation Layer not Data Layer.

Upvotes: 2

Related Questions