在运行时使用 Unity 属性注入注入 IPrincipal
在 ASP.Net MVC 2 应用程序中使用 Unity,我对正确实例化的控制器有各种依赖项。但是,我想确保用户的当前 IPrincipal 将通过注入传递到较低级别的服务、存储库等。
因此,在较低级别的服务中,我有类似的内容:
[Dependency] IPrincipal CurrentUser {get; set;}
如果我使用属性依赖注入,我不会得到什么我想要,因为控制器是在用户主体可用之前实例化的,并且在任何情况下 Unity 都不知道获取当前用户凭据。
所以我想要的是能够将当前用户的 IPrincipal (或者可能是 RolePrincipal)注入到控制器的依赖项之一中。
我该怎么做?
Using Unity in an ASP.Net MVC 2 app I have various dependencies on Controllers instantiated correctly. However, I want to ensure that the current IPrincipal for the user is going to be passed via injection to lower level Services, Repository etc.
Therefore in a lower level service I have something like:
[Dependency] IPrincipal CurrentUser {get; set;}
If I use Property Dependency Injection I do not get what I want because the Controller is instantiated BEFORE a User principal is available and in any case Unity does not know to get the current user credentials.
So what I want is to be able to inject the current user's IPrincipal (or probably RolePrincipal) into one of the dependencies for the Controller.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不走直接路线,直接分配就可以了。
Thread.CurrentPrincipal = 用户;
依赖注入很好,但不要让它妨碍最好的依赖注入器,即程序员。
Why not take the direct route, and just assign it.
Thread.CurrentPrincipal = user;
Dependency injection is good, but don't let it get in the way of the best dependency injector, the programmer.
虽然这个线程很旧,但看起来 Jon Kruger 的答案似乎直接回答了原始问题: http://jonkruger.com/blog/2009/04/13/hiding-threadcurrentprincipal-from-your-code/
While this thread is old, it looks like Jon Kruger has an answer that seems to directly answer the original question: http://jonkruger.com/blog/2009/04/13/hiding-threadcurrentprincipal-from-your-code/
为什么要注入呢?当前主体已作为
User
出现。这就是我们使用的,到目前为止效果很好。用户不应该在单个请求中进行更改,不是吗?Why inject it? The current principal is already present as
User
. That is what we use, and it works fine so far. The user shouldn't change within a single request, should it?