Search code examples
dependency-injectionninjecthttpcontext

Injecting HttpContext in Ninject 2


In my asp.net mvc application I'm using Ninject as a DI framework.

My HttpAccountService is used by my controllers to get info from and to cookies. For this I need the HttpContext.Current in the HttpAccountService. As this is a dependency I injected it throught the constructor as such:

kernel.Bind<IAccountService>()
    .To<HttpAccountService>()
    .InRequestScope()
    .WithConstructorArgument("context", HttpContext.Current);

Sadly this always binds to the same context which makes that after the first request finishes this context becomes outdated.

How should I correctly inject my HttpContext?


Solution

  • WithConstructorArgument has an overload that takes a Func<NinjectContext,T>, i.e., you can use:

    ... .WithConstructorArgument("context",ninjectContext=>HttpContext.Current);

    which will call the provided 'callback' lambda within the request processing and obtain the correct value at that point in time [as opposed to you calling the other overload and supplying a constant value which gets computed at Bind<> time].

    (If you're not trying to Mock the context, I assume you'll consider using it inline)