views:

214

answers:

2

Hello,

I was wondering how I could bind the IPrincipal to HttpContext.Current.User in Asp.net Mvc with Ninject.

Friendly greetings,

Pickels

Edit:

Not sure if it matters but I use my own CustomPrincipal class.

+1  A: 

Think I got it:

public class PrincipalProvider : IProvider
{
    public object Create(IContext context)
    {
        return HttpContext.Current.User;
    }

    public System.Type Type
    {
        get { return typeof(CustomPrincipal); }
    }
}

And in my NinjectModule I do:

Bind<IPrincipal>().ToProvider<PrincipalProvider>();

If this is wrong or not complete please let me know and I'll adjust/delete.

Pickels
+6  A: 

You can do this without the need for a provider in your NinjectModule:

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

Note, I included .InRequestScope() to ensure that the value of the method is cached once per HTTP request. I'd recommend doing so even if you use the provider mechanism.

Peter Meyer
Wow thanks, that is a great tip.
Pickels
No problem, hope it helps!
Peter Meyer