Asp.net Mvc: Ninject - IPrincipal
Asked Answered
U

2

14

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.

Upstretched answered 28/4, 2010 at 15:53 Comment(0)
P
27

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.

Pomade answered 28/4, 2010 at 18:19 Comment(0)
U
2

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.

Upstretched answered 28/4, 2010 at 16:42 Comment(1)
is it possible to persist the IProvider over different layers, including ones that do not reference the web?Knife

© 2022 - 2024 — McMap. All rights reserved.