Alex Rivera | Logout

Do I need dependency injection in NodeJS, or how to deal with ...?

Asked 2012-02-12T17:19:47.380
306

I currently creating some experimental projects with nodejs. I have programmed a lot Java EE web applications with Spring and appreciated the ease of dependency injection there.

Now I am curious: How do I do dependency injection with node? Or: Do I even need it? Is there a replacing concept, because the programming style is different?

I am talking about simple things, like sharing a database connection object, so far, but I have not found a solution that satisfies me.

Edit
Report

1 Answer

1

It depends on the design of your application. You can obviously do a java like injection where you create an object of a class with the dependency passed in the constructor like this.

function Cache(store) {
   this._store = store;
}

var cache = new Cache(mysqlStore);

If you are not doing OOP in javascript, you can make an init function that sets everything up.

However, there is another approach that you can take which is more common in an event based system such as node.js. If you can model you application to only(most of the time) act on events then all you need to do is to set everything up(which I usually do by calling an init function) and emit events from a stub. This makes testing fairly easier and readable.

answered 2012-02-12T19:19:49.297

Your Answer