开发者

Binding Ninject depending on Controller requests

I'm just learning Ninject and how to implement it in MVC situation. I'm trying to find out what the best way/practice is to setup the following scenario.

I have an Team Object, which will be reused throug开发者_运维百科h out the application, what I need to do is have Ninject resolve the binding automatically depending on where the request is coming from.

In my NinjectController factory I currently have a Service that resolves a Team to its proper repository

Bind<ITeamRepository>().To<SwimTeamRepository>() // non-space characters to enable edit submission

But if the request is coming in from SoccerController, I need to bind:

Bind<ITeamRepository>().To<SoccerTeamRepository>()

Should this be done conditionally, set up separate services? What is the best approach here? Or am I completely off the rail here...


It sounds like you might be wanting to use contextual binding. If that doesn't help, perhaps you could rephrase the question so I have a better idea of exactly what you're looking for.

This makes more sense after the edit. I'm not entirely sure how you have your application structured, but I would probably pass the ITeamRepository to the controller and the constructor would look something like this.

public SoccerController(ITeamRepository repository)
{
    _repository = repository;
}

public SwimmingController(ITeamRepository repository)
{
    _repository = repository;
}

And then the bindings:

Bind<ITeamRespository>().To<SoccerRepository>().WhenInjectedInto(typeof(SoccerController));
Bind<ITeamRespository>().To<SwimmingRepository>().WhenInjectedInto(typeof(SwimmingController));


@Timothy Strimple's answer is largely correct (hence my +1) except:

  1. Its for Ninject v1 - the CodePlex site needs to disappear as everything now lives on github
  2. you can express the fact that the binding to use is dependent on the controller involved via conditional binding -- there's an example in the wiki


In your controller's constructors you should pass in either an interface or abstract implementation of the type that Ninject will provide a concrete type for.

public SomeController(IRepositoryType repository) {
}

In the NinjectControllerFactory class you'll have the binding set up like this:

Bind.<IRepositoryType>()
    .To<DatabaseRepository>()
    ;

If your concrete implementation needs constructor arguments you can pass them in at the time they're bound.

Bind.<IRepositoryType>()
    .To<DatabaseRepository>()
    .WithConstructorArgument("connStr",
        "some_connection_string_here"
    );

Hope this points you in the right direction. ;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜