Accessing the Identity object in a MVC repository

笑着哭i 提交于 2019-12-08 13:29:02

问题


I have a pretty generic repository that does basic CRUD for many of my business entities. The entities enherit form a generic object that has a few fields I maintain for all objects. eg. ModifiedBy, CreatedBy, CreatedDate, ModifiedDate.

These fields ModifiedBy and CreatedBy will always be set before any update/save.

My questions is: Is there any way to gain access to the Identity object from my MVC web application in my repositories? I was hoping to set the modifiedby to the identity user for any update in one shot??

Best Regard, Rod


回答1:


Well, you could access HttpContext.Current.User.Identity directly in your repositories, but I wouldn't recommend it as it will make your repositories HttpContext-dependent.

Alternatives:

  • Add an explicit IIdentity parameter in your Create/Update methods, e.g. void Update(T entity, IIdentity user)
  • Decouple the logic of "getting the current user", e.g.:

    class GenericRepository<T>: IRepository<T> {
        private readonly ICurrentUserFetcher currentUserFetcher;
        public GenericRepository<T>(ICurrentUserFetcher currentUserFetcher) {
            this.currentUserFetcher = currentUserFetcher;
        }
        public void Update(T entity) {
            var currentUser = currentUserFetcher.Get();
            ...
        }
    }
    interface ICurrentUserFetcher {
        IIdentity Get();
    }
    class WebCurrentUserFetcher: ICurrentUserFetcher {
        public IIdentity Get() {return HttpContext.Current.User.Identity;}
    }
    

    Or even simpler:

    class GenericRepository<T>: IRepository<T> {
        private readonly Func<IIdentity> currentUserFetcher;
        public GenericRepository<T>(Func<IIdentity> currentUserFetcher) {
            this.currentUserFetcher = currentUserFetcher;
        }
        public void Update(T entity) {
            var currentUser = currentUserFetcher();
            ...
        }
    }
    var repo = new GenericRepository<Person>(() => HttpContext.Current.User.Identity);
    

    Use an IoC container to wire things up.



来源:https://stackoverflow.com/questions/2946042/accessing-the-identity-object-in-a-mvc-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!