2011-10-24 40 views
7

我看到以下两个示例用于注入用户的IPrincipal:MVC3 + Ninject:注入User IPrincipal的正确方法是什么?

方法1:

kernel.Bind<IPrincipal>() 
    .ToMethod(context => context.Kernel.Get<RequestContext>().HttpContext.User) 
    .InRequestScope(); 

方法2:

kernel.Bind<IPrincipal>() 
    .ToMethod(context => HttpContext.Current.User) 
    .InRequestScope(); 

有两个有什么区别?是首选吗?

+0

如何使用Autofac完成上述操作? – lafama

+0

找到我的答案http://stackoverflow.com/questions/2824649/passing-asp-net-user-by-dependency-injection – lafama

+0

你需要使用Ninject.Web.Common for'InRequestScope'扩展方法 –

回答

5

这两种方法是相同的。两者都将返回当前HTTP请求的HttpContext对象。

+0

如果是这样的话,我显然会选择更简洁的选项。任何想法为什么方法1中的“context.Kernel.Get”的所有麻烦? – Shawn

+0

如果您使用的上下文是另一种类型的ContextProvider,则需要第一个示例。由于您通过System.Web全局使用HttpContext提供程序,因此不需要第一个。 –

+0

非常好。谢谢。 – Shawn

相关问题