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...
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:
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. ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With