Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top