问题
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