Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is HttpContextBase being registered with ninject? I didn't explicitly bind it

I created a binding for HttpContextBase in my NinjectWebCommon.RegisterServices method, but when I try to reference it in my controllers or services I get an error message.

Here's the binding:

kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current)).InRequestScope();

Here's the error message:

Error activating HttpContextBase
More than one matching bindings are available.
Activation path:
 2) Injection of dependency HttpContextBase into parameter abase of constructor of type HomeController
 1) Request for HomeController

Suggestions:
 1) Ensure that you have defined a binding for HttpContextBase only once.

If I remove the binding, then it appears to do what I wanted (resolves to HttpContextWrapper), but I'm wondering how this gets registered?

like image 482
BlakeH Avatar asked Jun 06 '13 12:06

BlakeH


2 Answers

but I'm wondering how this gets registered?

Look at the source code of the MvcModule.cs and your question will be immediately answered:

this.Kernel.Bind<HttpContext>().ToMethod(ctx => HttpContext.Current).InTransientScope();
this.Kernel.Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope();
like image 194
Darin Dimitrov Avatar answered Sep 20 '22 15:09

Darin Dimitrov


I see the binding being registered by Ninject.Web.Common v3.2.3.0

If you are trying to mock the binding in your unit tests, you must remove it first like this:

// WebCommonNinjectModule loads HttpContextBase. We need to remove it
var httpContextBaseBinding = kernel.GetBindings(typeof(System.Web.HttpContextBase)).FirstOrDefault();
kernel.RemoveBinding(httpContextBaseBinding);
kernel.Bind<System.Web.HttpContextBase>().ToMethod(m => httpContextBaseMock.Object);
like image 45
jsgoupil Avatar answered Sep 20 '22 15:09

jsgoupil