tiny unobtrusive IoC container (<270 bytes gzip)
a tiny (<270 bytes gzip), unobtrusive IoC container that lazily instantiates any type from standard factories.
features
- unobtrusive: minimal footprint on the code of the modules that are wired together. instances are created by standard factories that deconstruct their dependencies from a plain javascript object they receive as argument.
- lazy: instantiates dependencies only when required.
- fully compatible with any form of module import.
does not monkeypatch
require
. - fully compatible with minification. does not stringify factories to extract dependency names.
- fully compatible with any test framework. simply mock dependencies in tests, without any additional tools.
- typescript support.
- tiny: less than 270 bytes gzip.
Example
see the full example in this directory.
run the example in your browser locally with npm run example
or online here.
index.ts
:
// declare the shape of the IoC container // instantiate a container of the above shape,// and retrieve a corresponding factory registration function// register factories from a mapuse// or register factories individuallyuse'db', dbFactoryuse'dbname',DB_NAME // each of the above returns the container object, as well as: service.save.thenlog'save:' // alternatively, inject directly (without registering):uselog'version:'version
refer to the API section for detailed usage.
service.ts
:
the code for the service factory is not tainted by the DI container implementation:
it merely implements IoC by deconstructing its dependencies
from the plain javascript object it receives as argument.
db.ts
:
likewise, the db factory deconstructs its single dependency from its argument.
it is completely unaware that the instances it creates will be
injected into the service by the DI container.
API
declare declare
TypeScript
although this library is written in TypeScript, it may also be imported into plain JavaScript code: modern code editors will still benefit from the available type definition, e.g. for helpful code completion.
License
Copyright 2018 Stéphane M. Catala
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and Limitations under the License.