1

I am developing an application and using Ninject for DI. I would like to be able to inject a different object into a given method depending on the solution configuration I am using. Namely, in a "mock" configuration mode I would like to inject a mock object and in the debug/release configurations I would like to inject a real object.

Having read Ninject and configuration I understand that XML configs offer such a possiblity. However, I would like to do this without the XML if possible. (I tend to agree with Ninject that injection details shouldn't be configurable in the published product...) I am also aware that I could use preprocessor directives to do this. What I would like to know is if this capability exists in Ninject, or if I need extensions/workarounds to accomplish it.

Community
  • 1
  • 1
Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
  • 1
    related http://stackoverflow.com/questions/1465849/using-ioc-for-unit-testing Dont use DI in unit tests and [think hard before doing too much testing with or of DI config](http://blog.ploeh.dk/2011/12/21/TestingContainerConfigurations.aspx). If you do decide to go down the road, the way to package up sets of config in Ninject is with Modules - you can pass various ones to the Kernel upon construction – Ruben Bartelink Oct 17 '12 at 00:36
  • Thank you for the great articles. I hadn't considered the (very valid) points against using DI for unit testing. I will look into modules, as I would still like to use DI for general testing of my user interfaces. Thanks again. – Levi Botelho Oct 17 '12 at 06:22
  • Worth having a search on SO for Ninject tests / DI tests / DI unit tests or similar - this has been covered with good answers before – Ruben Bartelink Oct 17 '12 at 08:03
  • My case is a particular one that I did not explain for simplicity's sake in the question. It requires specific manual testing on an algorithm which is best managed with a separate solution configuration. The modules + preprocessor directives do what I need here. Automated or even general testing was not my intention when I asked the question. I very much appreciate the information on the UTs though--great for future reference. – Levi Botelho Oct 17 '12 at 08:38

1 Answers1

7

What about preprocessor directives in your ninject configuration. It should do what you want.

#if DEBUG
        kernel.Bind<IMyService>().To<MyServiceMock>();
#else
        kernel.Bind<IMyService>().To<MyService>();
#endif
mipe34
  • 5,596
  • 3
  • 26
  • 38
  • That is effectively what I ended up doing (see my last comment on my question) and it has worked well. – Levi Botelho Nov 09 '12 at 19:22
  • Fine, but you did not post it as answer to your question. Now it is easier for other developers to find solution for similar issue. – mipe34 Nov 09 '12 at 20:18