views:

159

answers:

2

I'm using Ninject 2 with an ASP.NET MVC web app. All the dependencies are handled properly down the stack (Controllers->Services->Repositories). However I have some classes in the Services project that aren't in that "chain" that I also want to inject when the app starts. How do I get Ninject to recognize them? I have public properties with [Inject] attributes but when the app runs, they're null. What am I missing?

Here is my MvcApplication class:

public class MvcApplication : NinjectHttpApplication
{
    protected override void OnApplicationStarted() {
        RegisterRoutes(RouteTable.Routes);
        RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    protected override IKernel CreateKernel() {
        var modules = new INinjectModule[] {
            new Services.ServiceModule(),
            new Data.DataModule()
        };

        var kernel = new StandardKernel(modules);

        return kernel;
    }

    // route registration removed
}

I double checked both modules to make sure that the correct bindings exist.

Sample from a module:

public class ServiceModule : NinjectModule
{
    public override void Load() {
        Bind<IAccountService>().To<AccountService>();
        ....
    }
}
A: 

Are you overriding CreateKernel()? You need to do that and do your binding in there.

J.R. Garcia
Yeah I'm doing that. I'll update the question
John Sheehan
Added code and tried to clarify better
John Sheehan
Everything looks fine there. Can you post some of the code in one of your modules?
J.R. Garcia
Wow... That all looks good to me. You may want to post that to the Google Group. Ian Davis and Nate Kohari are ridiculously quick to respond.
J.R. Garcia
+2  A: 

In order for Ninject to inject dependencies, you have to create the object using the kernel. That's easy for objects in the natural dependency chain (ie. in your app, Controllers->Services->Repositories), but can be tricky for those outside of it.

You have to either add the additional types as dependencies of one of the types that is created in the natural chain, or somehow get a hook on the kernel and call Get<T>. To do that, you might have to use a static service locator.

Nate Kohari