Koa: Dependency injection implementation

Created on 26 Dec 2014  路  11Comments  路  Source: koajs/koa

Would be nice to have something like this

var object = {};

app.di.factory('User', function () {
  return object;
});

router.get('/path', function *(User, next, db) {
  expect(User).to.be.equals(object);
  yield next;
});

All 11 comments

I'm not sure what you're trying to achieve. Could you elaborate a little on what problem you're trying to solve?

:-1:

I dont think javascript need Dependency injection concept.

Would be really sweet if we had something like require.

var User = require('../user.js');

Wait we already do ;-)

It should work in the same way as it works in angular.js. This approach allows to mock dependencies of the module a lot easier and you don't have do deal with relative paths (which I find a bit painful when project becomes big).

If so, build something on top of Koa, I don't see this going into core Koa :)

If you're looking to mock dependencies (require() statements in Node.js) I can recommend using proxyquire. If you're having trouble with relative paths, I can suggest trying a flat directory structure with a module per domain and a package.json in each folder. For me that's made my applications more loosely coupled. You can take that approach a step further by using scoped packages and linklocal, but it's not necessary.

Dependency Injection (DI) tries to solve problems that fall in the same domain as require(). Since we're already using require() (and liking it too!) DI doesn't make a lot of sense. However, if you're set on having it on top of Koa you can always build it yourself!

I hope this was helpful!

@hallas I had that feeling as well :))
@yoshuawuyts oh, okay. this makes sense. And proxyquire looks good!

Thank you for your responses.

Sorry about the cold welcome ;)

No worries, I understand you. haha :) That was just my lack of knowledge.

@rainder you can try to use bearcat with koa

Was this page helpful?
0 / 5 - 0 ratings