n nisli
GitHub

Dependency injection

nisli has built-in DI. Inject a service anywhere in the tree without prop-drilling or module-level globals — and the class itself is the token.

inject

inject(Service) returns a singleton, auto-created on first use. No registration, no provider boilerplate — the class is the token.

import { component, inject, html } from '@nisli/core';

class Clock {
  now() {
    return new Date().toLocaleTimeString();
  }
}

component('x-now', () => {
  const clock = inject(Clock); // singleton, auto-created
  return html`<time>${clock.now()}</time>`;
});

provide

Override what a token resolves to — a mock in tests, or a configured instance. Call provide() before the consumer injects.

import { provide } from '@nisli/core';

class Clock {
  now() {
    return new Date().toLocaleTimeString();
  }
}

// Override what a token resolves to — e.g. a fixed clock in a test.
provide(Clock, () => ({ now: () => '12:00:00' }));

Tokens for non-class values

For values that aren’t classes (config objects, primitives), create a typed token with createToken().

import { createToken, inject, provide } from '@nisli/core';

const ApiUrl = createToken<string>('ApiUrl');

provide(ApiUrl, () => 'https://api.nisli.dev');

export const url = inject(ApiUrl); // string