smart-factory
Simple but powerful, functional-programming ready Dependency Injector/Container library for node.js.
dependency injection library for not only classes but also functions, strings, numbers, ... and all objects in the world.
features
- simple syntax, easy to use
- functional-programming ready
- lightweight
- built-in typescript supports
- supports lazy-instantiation
installation
npm i smart-factory
simple usage
javascript + es6
const init injectable resolve = ; // module namesconst ModuleNames = MSG_PROVIDER: 'MSG_PROVIDER' MSG_PRINTER: 'MSG_PRINTER' GREETER: 'GREETER'; // regiser message provider function to container; // register message printer function to container; // register greeter function to container.; { // awaiting container ready ;};
typescript + es2015
; ;;; injectable Modules.MSG_PROVIDER, // module name , // dependencies ; injectable Modules.MSG_PRINTER, , console.logmsg; injectable Modules.HELLO_FUNC, , // has dependencies to MsgProvider, MsgPrinter ; ;
API reference
async init(opts?: ContainerOptions): Promise<void>
initialize container. after init() executed, you can retreive a modules from container.
type ContainerOptions
key | mandantory | default | description |
---|---|---|---|
debug?: boolean | no | false | show container logs. for debug purpose. |
includes?: string[] | no | null | specify path for modules which calls injectable(). |
excludes?: string[] | no | null | specify path for exceptional modules. |
example
;
injectable(key: string, deps: string[], instantiator: Instantiator): void
register modules to container. the dependencies deps[]
will be injeted before the module instantiated.
after all dependencies meets requirements, the modules will be instantiated and registered to container with name key
.
the instantiator
is your async function that preparing instance from given dependencies deps[]
.
example
;; injectable 'COFFEE_MAKER', // module name , // required dependencies // the "Instantiator": returns coffeeMaker function. ;
resolve<T>(key: string): <T>
resolves module from container. with typescript, you can specify type.
example
;
set<T>(key: string, instance: T): void
replace an instance in container with given key and instance. you can use this feature in the test codes.
;
clear(): void
clear all instances in container
;
More complicated examples
There are a more complicated examples that using smart-factory. you can learn how to manage complicated dependencies (ex: configuration, database, models..) for complicated application with the smart-factory.
- Chatpot-Room-Server
- chatting-room server written with Typescript, smart-factory
- configurations, mysql, models, api endpoints
- shows handling modules names and types with typescript way.