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?

Shawn
  • 1,871
  • 2
  • 21
  • 36
  • How can I accomplish the above using Autofac? –  Jun 07 '12 at 19:55
  • Found my answer http://stackoverflow.com/questions/2824649/passing-asp-net-user-by-dependency-injection –  Jun 07 '12 at 20:09
  • you'll need using Ninject.Web.Common for `InRequestScope` extension method – Simon_Weaver Dec 14 '12 at 08:59
  • 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? – GBreen12 Jun 26 '14 at 16:57

1 Answers1

7

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

Jeff Reddy
  • 5,551
  • 9
  • 55
  • 88
  • 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? – Shawn Oct 24 '11 at 19:30
  • 1
    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. – Jeff Reddy Oct 24 '11 at 20:00