Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add auto resolver #73

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/container.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ function Container() {
this._resolvers = [];

this.resolver(require('./resolvers/id')());
this.resolver(require('./resolvers/auto')(this));
}

// Inherit from `EventEmitter`.
Expand Down
36 changes: 36 additions & 0 deletions lib/resolvers/auto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Automatic interface resolver.
*
* Automatically resolves an interface to an object that implements that
* interface. Automatic resolution reduces the amount of configuration that
* must be specified.
*
* For consistency and saftey in the development cycle, such resolution succeeds
* if and only if there is one object within the container that implements the
* interface. If multiple objects implement the interface, automatic resolution
* would be ambiguous, and is therefore not performed. In such cases, the exact
* object to resolve can be explicitly declared in configuration.
*
* @return {function}
* @protected
*/
module.exports = function(container) {

return function(iface, pid) {
var specs = container.components()
, candidates = []
, spec, i, len;
for (i = 0, len = specs.length; i < len; ++i) {
spec = specs[i];
if (spec.implements.indexOf(iface) !== -1) {
candidates.push(spec.id);
}
}

if (candidates.length == 1) {
return candidates[0];
} else if (candidates.length > 1) {
throw new Error('Multiple objects implement interface \"' + iface + '\" required by \"' + (pid || 'unknown') + '\". Configure one of: ' + candidates.join(', '));
}
};
}