Injecting HttpContext in Ninject 2

天大地大妈咪最大 提交于 2019-12-03 12:36:26

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/3617447/injecting-httpcontext-in-ninject-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!