开发者

Injection question when using Ninject 2 in ASP.NET MVC application

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开发者_Go百科 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>();
        ....
    }
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜