Ninject binding based on controller requests

I'm just learning Ninject and how to implement it in an MVC situation. I am trying to figure out which best way / practice is to set up the following scenario.

I have a Team Object that will be reused from within the application, what I need to do is that Ninject will enable the binding automatically depending on where the request is coming from.

In my NinjectController factory, I currently have a Service that resolves a command to its correct repository.

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

But if the request comes from SoccerController, I need to bind:

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

If you do this conditionally, configure individual services? What is the best approach here? Or I'm completely not in the mountains here ...

+8
c # asp.net-mvc ninject binding
source share
3 answers

It looks like you can use contextual binding . If this does not help, perhaps you can rephrase the question so that I better understand what exactly you are looking for.

This makes sense after editing. I'm not quite sure how your application is structured, but I would probably pass 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)); 
+12
source share

@Timothy Strimple answer is pretty much correct (hence my +1), except:

+4
source share

In controller constructors, you must pass either an interface or an abstract implementation of the type that Ninject will provide a specific type for.

 public SomeController(IRepositoryType repository) { } 

In the NinjectControllerFactory class, you will have a binding configured as follows:

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

If your particular implementation requires constructor arguments, you can pass them at the time of binding.

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

Hope this indicates that you are in the right direction. ;

+1
source share

All Articles