从数据层访问HttpContext和用户身份

编程入门 行业动态 更新时间:2024-10-17 02:53:28
本文介绍了从数据层访问HttpContext和用户身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在我的所有其他实体(Fluent Nhibernate)继承的基本实体上实现AdditionalBy/ChangedBy类型字段.

I need to implement AddedBy/ChangedBy type fields on my Base Entity that all other entities inherit from ( Fluent Nhibernate ).

从我的存储库/数据层访问HttpContext.User.Identity可能不是一个好主意. 抓住我的用户(当前身份)信息以记录添加或更改记录的人的最佳方法是什么? 将整个应用程序重构为将用户信息包括在存储库调用中将是很愚蠢的.我敢肯定有一种更好,更通用的方法.

Accessing HttpContext.User.Identity from within my Repository/Data layer is probably not a good idea.. or is it ? What's the best way to grab my user ( current identity ) information to record who the records were added or changed by ? Re-factoring the entire application to include user information in repository calls would be silly. I'm sure there is a better, more generic way.

推荐答案

从数据层访问HttpContext会使工作变得更加困难,特别是在使用单元测试的情况下.解决方案是创建一个服务,以提供应用程序范围的用户信息,例如:

Access the HttpContext from the Data Layer makes the life harder, specially if you use Unit Tests. The solution is to create a service to provide application wide user information, something like:

public interface ICurrentUserService { string UserName {get;} string UserId {get;} string HostIP {get;} // etc. }

然后,您可以实施具体的服务并使用您的 首选的IoC容器.

Then you can implement the concrete service and inject it using your preferred IoC container.

public class CurrentWebUserService : ICurrentUserService { // implement interface members public CurrentWebUserService(HttpContext context) { ... } public string UserName { get { ... } } // etc. } // maybe you want a stub service to inject while unit testing. public class CurrentUserServiceStub : ICurrentUserService { } // data layer public class MyDaoService { public DaoService(ICurrentUserService currentUser) { ... } }

更多推荐

从数据层访问HttpContext和用户身份

本文发布于:2023-11-17 12:30:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1610007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份   数据   用户   HttpContext

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!