MVC3 + Ninject: What is the proper way to inject the User IPrincipal?
Asked Answered
S

1

7

I have seen the following two example for injecting the User IPrincipal:

Method 1:

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

Method 2:

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

Is there any difference in the two? Is one preferred?

Skiing answered 24/10, 2011 at 14:43 Comment(4)
How can I accomplish the above using Autofac?Competitor
Found my answer #2825149Competitor
you'll need using Ninject.Web.Common for InRequestScope extension methodCalculate
When I try to do these method 1 throws a null exception and method 2 gives me an empty IPrincipal, any idea why it wouldn't be working correctly?Eurythmic
A
7

The two methods are identical. Both are going to return the HttpContext obect for the current HTTP Request.

Apocalyptic answered 24/10, 2011 at 15:42 Comment(2)
If that's the case, I'm obviously going to choose the more concise option. Any idea why all the trouble of "context.Kernel.Get" in Method 1?Skiing
The first example would be needed if the context you were using was of another type of ContextProvider. Since your using the HttpContext provider globally available via System.Web, there is no need for the first.Apocalyptic

© 2022 - 2024 — McMap. All rights reserved.