doser

Lightweight ES2015+ dependency injection written in ES6

Usage no npm install needed!

<script type="module">
  import doser from 'https://cdn.skypack.dev/doser';
</script>

README

doser

version downloads license

Lightweight ES2015+ dependency injection written in ES6

Installation

npm install doser --save

Usage

import Doser from 'doser';

class DatabaseConnection {
    constructor(url) {...}
    query() {...}
}
const DATABASE_CONNECTION_URL = 'mysql://user:password@localhost';

class ProductService {
    constructor(database) {
        this.database = database;
        ...
    }
    list() {
        return this.database.query(...);
    }
}

const container = new Doser();

container.registerPrimitive('DATABASE_CONNECTION_URL', DATABASE_CONNECTION_URL, true);
container.register('database', (inject) => new DatabaseConnection(inject('DATABASE_CONNECTION_URL'), true));
container.register('product_service', (inject) => new ProductService(inject('database')));

container.has('product_service'); //true
container.has('unknown_key'); //false

const product_service = container.get('product_service');
product_service.list();

const proxy = container.makePublicProxy(); //returns a freezed object with getters for each registered public key
proxy.product_service.list();