2

In many cases in C# i can use interface to get loose coupling between components.

for example a component could retrieve an

ITextFileReader reader = dic.Resolve<ITextFileReader();

No matter which implementation is currently bound. For example in test environment i could pass a spy or mock.

In node.js i use

require('./myTextReader.js")

but there is a fix dependency to that specific file. what is the best practice to get the described behavior f orm above in node.js implemented?

What I don't want to do is to have some facade / wraper with "If...." clauses which may decide who to delegeate the call

Also i want to avoid to have the setup configuration as a part of my production code. the setup code should be outside the domain logic in the Application Composition layer.

So as best thing i would have something like a component registration, and consumer which just use the registration information to get there instance (without knowing anything ábout the registration details )

i found di.js which seems to be the angular.js approach. I could also implement some kind of di by myself. But reinventing the wheel is often a bad decission.

What is the current best practice / state of the art to do this?

Boas Enkler
  • 12,264
  • 16
  • 69
  • 143
  • Take a look at the accepted answer here: http://stackoverflow.com/questions/9250851/do-i-need-dependency-injection-in-nodejs-or-how-to-deal-with – Timothy Strimple Dec 10 '14 at 18:45
  • Well its not the same thing. i don't want facade classes or extens supertypes. what i really want is indirection, inversion of control. perhaps wasn't clear enough on this point, i ll improve it – Boas Enkler Dec 11 '14 at 10:13
  • What you're doing in your example is not Inversion of Control. It is a Service Locator Pattern. The Service Locator Pattern is often used with IoC, but it's not necessary. Regardless, it's trivial to implement your own Service Locator in Node, or you can search NPM. https://github.com/jaredhanson/node-servicelocator – Timothy Strimple Dec 11 '14 at 19:00
  • 2
    And that still misses the point of the linked answer. You don't need your typical IoC infrastructure because of the Node module system. Just design your Node modules to accept dependencies in their constructor and then `var module = require('./mymodule')(dep1, dep2);` – Timothy Strimple Dec 11 '14 at 19:02
  • @TimothyStrimple that is what I was considering doing. Is this common practice? – ryandawkins Aug 24 '16 at 15:17

0 Answers0