我正在使用具有存储库模式的服务层。 controller依赖于service层,service层依赖于repository。
出于授权目的,我必须将登录的用户信息传递到存储库层,并且考虑到我似乎有一个广泛的注入(inject)链,我正在尝试确定将用户信息注入(inject)存储库的最佳方法:
controller -> service(s) -> repositories -> logged in user info.
我想简单的方法是将用户信息传递给被调用的服务方法(即 FindById(int primaryKey, User currentUser)
等)
但与注入(inject)用户信息相比,这似乎非常有限且存在问题。
解决这个问题的推荐方法是什么?
我对文章中的人如何实现 ICurrentUserFetcher 感到有点困惑。我假设这会提供 IIdentity 不可用的额外属性,但这篇文章并没有说得很清楚。
class GenericRepository<T>: IRepository<T> {
private readonly ICurrentUserFetcher 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);
最佳答案
登录后将用户信息赋值给当前主体。 Google 关于 IPrincipal
和 IIdentity
。这两个类是 .NET 中处理当前登录用户的内置方式。
要访问用户,只需使用 Thread.CurrentPrincipal.Identity
。但是,我不会在存储库中使用该属性,而只会在服务类中使用。这样做的原因是存储库不应该负责告诉哪个用户要为哪个用户获取信息。
要为每个请求分配用户,您必须使用 global.asax 中的 PostAuthenticate 事件。
关于asp.net-mvc-3 - 将经过身份验证的用户依赖注入(inject)我的存储库类的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16742633/