依赖注射传递ASP.NET用户 [英] Passing ASP.NET User by Dependency Injection
问题描述
在我的web应用程序我有需要访问当前已验证用户(HttpContext.User中)各种组件。
In my web application I have various components that need to access the currently authenticated user (HttpContext.User).
有两个明显的方式,组件可以访问此:
1)访问从HttpContext.Current获取用户
2)各地传递用户在构造函数中
There are two obvious ways a component can access this: 1) Accessing getting the User from HttpContext.Current 2) Passing the user around in constructors
- 是不理想的,因为它使测试难度和领带应用程序组件的网络关注,当他们真的不应该知道这一点。
- 仅仅是混乱和复杂的一切。
所以,我一直在思考在当前用户传递(或者仅仅是名称/ ID)使用IoC容器它需要的任何组件(通过依赖注入)。
So I've been thinking about passing in the current user (or perhaps just the name/id) to any component that needs it using an IoC container (via dependency injection).
时使用这种技术来提供当前ASP.NET用户对应用程序的部分人?或者说,这听起来像一个明智的做法?我想知道这是如何制定的人。
Is anyone using this technique to supply the current ASP.NET user to parts of the application? Or, Does this sound like a sensible approach? I would like know how this has worked out for people.
感谢
更新:
感谢拉吉一个很好的例子。如果任何人有使用AutoFac一个类似的例子这将是更AP preciated!
UPDATE: Thanks to Raj for a great example. If anyone has a similar example using AutoFac it would be much appreciated!
UPDATE2:谢谢你的答案,希望我能分裂接受
UPDATE2: Thanks for the answers, wish I could have split the accept!
推荐答案
在autofac:
builder.Register(C => HttpContext.Current.User.Identity).HTT prequestScoped();
builder.Register(c => HttpContext.Current.User.Identity).HttpRequestScoped();
这篇关于依赖注射传递ASP.NET用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!