“Dependency injection” is a somewhat scary term to explain loading modules and making sure
memory footprint is minimal.
I’ve been thinking a lot about Angular’s
$injector and how I might build a dependency injector
A thing that creates things
À la angular, I wanted an
injector as the global namespace, a
module method that allows
me to both read and create modules. Let’s start with creating a module.
We want the interface to be something like
Where the name of the module is the first argument, the second argument is
an array of dependencies, and the third argument is the module’s prototype (methods and attributes).
If there is only the first argument, the injector assumes the module has already been defined and returns the module’s prototype.
Now that we can read and write modules, let’s try seeing if a module’s dependencies have been loaded before calling methods.
The angular-style of injecting dependencies is:
Raising Errors when Dependencies Are Not Met
If the specified dependency is not already defined in
injector._modules, raise an error:
Passing Modules to functions
While in the loop, if the
typeof the element is a function, we can assume it is the last
element of the array, and invoke it with each of the modules.
This code must come before the error-raising code above. That is, a
return is necessary after the
function’s invocation to prevent the “module not met” dependency error.
We now have an interface like this:
Now that we have a way to create, read, and depend on modules, where do we go from here?
I was thinking it would be nice to be able to asynchronously load modules, but I’ll leave that for another day.
Here’s the dependency injector all together:
Edit this Post