1

I'm using Ninject 3.0 to inject service layer data access classes into my controllers. I would like to add the client's domain user ID to these classes at runtime, but cannot figure out what approach I should use. Currently my NinjectModule looks something like this:

public class NinjectBindModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISomeRepo>().To<SomeRepo>();
    }
}

My question, in two parts really is:

  1. Should I use WithConstructorArgument to get the user ID into SomeRepo, or something else (property?). Can I even do this in the bind module, or does it have to be done at the kernel or controller level?
  2. What method should I use to retrieve the client's domain user ID? I don't think I can use the Controller.User property at the kernel level or in the bind module, can I?
Community
  • 1
  • 1
AJ.
  • 16,368
  • 20
  • 95
  • 150

1 Answers1

5
public class NinjectBindModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISomeRepo>().To<SomeRepo>();
        Bind<IPrincipal>()
            .ToMethod(ctx => HttpContext.Current.User)
            .InRequestScope();
    }
}

and then:

public class SomeRepo : ISomeRepo
{
    private readonly IPrincipal _principal;
    public SomeRepo(IPrincipal principal)
    {
        _principal = principal;
    }

    ... some methods that will have access to the principal
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928