Skip to content
This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
/ konteiner Public archive

Simple DI container for node.js applications

License

Notifications You must be signed in to change notification settings

petrmiko/konteiner

Repository files navigation

konteiner - simple zero-dependencies DI container for node.js apps

Warning

This package is no longer maintained and will not receive further updates.

Build Status Coverage Status

This module provides you means to:

  • register desired instantiable modules (functions, classes) to DI container
  • use the initialized dependencies in modules by obtaining them via getter on Konteiner instance, that is provided via constructor/parent function
  • having the modules initialized in lazy manner, ie. on first konteiner.get call

Usage

  • Install the dependency npm i --save @petrmiko/konteiner@latest
  • In JS code
const Konteiner = require('@petrmiko/konteiner')

const konteiner = new Konteiner()

// first we need to have some instance creators, here functions
const Logger = () => console
const Messenger = /** @type {Konteiner} */ (konteiner) => {
	const logger = konteiner.get(Logger)
	return {
		sendMessage(text) { logger.log(text) }
	}
}
// following lines will just register dependencies, init is made upon first get for affected dependencies
konteiner.register(Logger)
konteiner.register(Messenger)

const messenger = konteiner.get(Messenger) // this will actually invoke the constructor of Messenger (and Logger, since it is a dependency of demoMessenger)
messenger.sendMessage('Hello world!') // console.log will print out 'Hello world!'

If you want to load all dependencies in an directory, you can also do following.

const Konteiner = require('@petrmiko/konteiner')
const konteiner = new Konteiner({exclude: [
	'\\.test\\.' // all test files will be omitted from batch loading using .registerPath
]})

konteiner.registerPath('./src', {exclude: [
	'\\.test\\.',
	'index\\.js'
]}) // all but tests and index.js will be loaded. Overrides exclude from constructor for this call only

// then in place of use we need to know, what dependency creator was used to retrieve its instance
const Service = require('./src/service')

const someService = konteiner.get(Service) // all dependencies bound to Service will be now initialized
...

For more details, see API section.