4
votes

I have a .Net MVC 3.0 application and I'm using Ninject 3.0. I didn't install any nuget. I'm referencing Ninject.dll, Ninject.Web.Common.dll and Ninject.Web.Mvc.dll (and 2 others). I want to have dependencies injected in a custom HttpModule and I can't figure out how to make it work with a NinjectHttpApplication.

I have this error:

Error activating IntPtr
No matching bindings are available, and the type is not self-bindable.
Activation path:
3) Injection of dependency IntPtr into parameter method of constructor of type Func{IKernel}
2) Injection of dependency Func{IKernel} into parameter lazyKernel of constructor of type HttpApplicationInitializationHttpModule
1) Request for IHttpModule

Here is the code:

Global.asax

public class MvcApplication: NinjectHttpApplication
{
    ...
    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[]
        {
            new ServiceModule()
        };

        IKernel kernel = new StandardKernel(modules);

        return kernel;
    }
}

Web.Config

<httpModules>
    <add name="NinjectHttpModule" type="Ninject.Web.Common.NinjectHttpModule"/>
</httpModules>

CustomHttpModule.cs

public class CustomHttpModule : IHttpModule
{
    private ITesttService service;
    public CustomHttpModule(ITesttService service)
    {
        this.service = service;
    }
    ...
}

ServiceModule.cs

public class ServiceModule : NinjectModule  
{
    public override void Load()
    {
        ...
        Kernel.Bind<ITestService>().To<TestService>();
        Kernel.Bind<IHttpModule>().To<CustomHttpModule>().InSingletonScope();
    }
}

This binding solves my problem:

kernel.Bind<Func<IKernel>>().ToMethod(c => () => this.Kernel);

But according to this post on github, I'm not supposed to do it.

Can you someone tell me what I'm doing wrong or missing?

1

1 Answers

3
votes

Currently there is no good way to use the NinjectHttpModule when deriving from NinjectHttpApplication. The bootstrapper registers the HttpApplicationInitializationHttpModule for both ways and as soon as the NinjectHttpModule is loaded this module is loaded as well.

Unfortunately there is no good point where you can unload it.

I suggest you use the WebActivator instead on deriving from NinjectHttpApplication. It's the only proper way to get it running. You don't necessarily have to use nuget to setup your application that way. You can also add the same files manually and manually reference all required assemblies.