Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 through 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...

like image 421
keeg Avatar asked May 06 '11 18:05

keeg


3 Answers

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));
like image 51
Timothy Strimple Avatar answered Nov 11 '22 20:11

Timothy Strimple


@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
like image 21
Ruben Bartelink Avatar answered Nov 11 '22 21:11

Ruben Bartelink


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. ;

like image 24
Yuck Avatar answered Nov 11 '22 19:11

Yuck