views:

50

answers:

1

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?

A: 

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

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

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

Ruben Bartelink
That syntax doesn't seem to compile. It compiles with x=>HttpContext.Current, but this doesn't achieve the expected result.Could it be because I get my ninjectkernel from a (static) factory?
borisCallens
On further inspection it seems I now DO get the correct context, but my problem must lie somehwere else. Thx
borisCallens
for the record: it was because a RedirectToRoute resets that requests cookies.
borisCallens
Cool, edited in your point, thanks.
Ruben Bartelink