• Stars
    star
    247
  • Rank 164,117 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A compile-time powered Dependency-Injection container for Typescript that holds services and can produce instances of them as required.
Logo

A compile-time powered Dependency-Injection container for Typescript that holds services and can produce instances of them as required.

Downloads per month NPM version Dependencies Contributors License: MIT Support on Patreon

Description

This is a tiny library that brings Dependency-Injection to Typescript. There are several competing libraries out there, but this one is unique in the sense that:

  • It is seriously small.
  • It does its work on compile-time. The only runtime dependency is the DIContainer itself.
  • It doesn't ask you to reflect metadata or to annotate your classes with decorators. "It just works".
  • It maps interfaces to implementations. Most popular dependency injection systems for TypeScript doesn't do this. This allows you to truly decouple an abstraction from its implementation.
  • It supports the .NET generic reflection flavour: registerSingleton<Interface, Implementation>(). No need for anything else.

This library provides constructor-based dependency injection. This means that your classes will receive dependency-injected services as arguments to their constructors.

This library is a runtime dependency, but you need to transform your code with the DI Custom Transformer as part of your Typescript compilation step to make the reflection work.

Backers

Bubbles Christopher Blanchard Ideal Postcodes Xerox Trent Raymond scrubtheweb
Bubbles
Twitter: @usebubbles
Christopher Blanchard Ideal Postcodes Xerox Trent Raymond scrubtheweb

Patreon

Patrons on Patreon

Table of Contents

Install

npm

$ npm install @wessberg/di

Yarn

$ yarn add @wessberg/di

pnpm

$ pnpm add @wessberg/di

Usage

This library is meant to be super straightforward, super simple to use. The following examples hopefully shows that:

Registering services

To register services, simply instantiate a new service container and add services to it. Here's several examples of how you may do that:

import {DIContainer} from "@wessberg/di";

// Instantiate a new container for services
const container = new DIContainer();

// Register the service as a Singleton. Whenever the 'IMyService' service is requested,
// the same instance of MyService will be injected
container.registerSingleton<IMyService, MyService>();

// Register the service as a Transient. Whenever the 'IMyService' service is requested,
// a new instance of MyService will be injected
container.registerTransient<IMyOtherService, MyOtherService>();

// Rather than mapping a class to an interface,
// here we provide a function that returns an object that implements
// the required interface
container.registerSingleton<IAppConfig>(() => myAppConfig);

// You don't have to map an interface to an implementation.
container.registerSingleton<MyAwesomeService>();

Retrieving instances of services

Injecting instances of services into classes

...Works completely automatically. As long as your class is constructed via a DIContainer, and as long as the services it depends on are registered, the class will receive the services as arguments to its' constructor:

class MyClass {
  constructor(
    private myService: IMyService,
    private myOtherService: IMyOtherService,
    private myAwesomeService: MyAwesomeService
  ) {}
}

The true power of this library in comparison to others is that all of this mapping happens on compile-time. This is what enables you to depend on interfaces, rather than objects that live on runtime.

Getting instances directly from the DIContainer

Sure, you can do that if you want to:

// Gets a concrete instance of 'IMyService'. The implementation will
// depend on what you provided when you registered the service
const service = container.get<IMyService>();

Contributing

Do you want to contribute? Awesome! Please follow these recommendations.

Maintainers

Frederik Wessberg
Frederik Wessberg
Twitter: @FredWessberg
Github: @wessberg
Lead Developer

FAQ

This is pure magic. How does it work?

It may look like it, but I assure you it is quite simple. Read this answer for an explanation.

Is it possible to have multiple, scoped containers?

Sure. You can instantiate as many as you want to, as long as you make sure the Custom Transformer for DI get's to see the files that contain them.

License

MIT © Frederik Wessberg (@FredWessberg) (Website)

More Repositories

1

rollup-plugin-ts

A TypeScript Rollup plugin that bundles declarations, respects Browserslists, and enables seamless integration with transpilers such as babel and swc
TypeScript
490
star
2

cjstoesm

A tool that can transform CommonJS to ESM
TypeScript
380
star
3

Polyfiller

Never worry about polyfills again.
JavaScript
125
star
4

scroll-behavior-polyfill

A polyfill for the 'scroll-behavior' CSS-property
TypeScript
102
star
5

browserslist-generator

A library that makes generating and validating Browserslists a breeze!
TypeScript
86
star
6

ts-evaluator

An interpreter for Typescript that can evaluate an arbitrary Node within a Typescript AST
TypeScript
84
star
7

DI-compiler

A Custom Transformer for Typescript that enables compile-time Dependency Injection
TypeScript
77
star
8

ts-clone-node

A library that helps you clone Nodes from a Typescript AST
TypeScript
32
star
9

pointer-events

A Level 2 spec-compliant Pointer Events polyfill with first-class Shadow DOM support
TypeScript
17
star
10

sandhog

A virtual Open Source project maintainer
TypeScript
15
star
11

color

A library of well-tested helper methods for working with colors.
TypeScript
13
star
12

connection-observer

An API that provides a way to asynchronously observe the connectedness of a target Node inside a document
TypeScript
13
star
13

intl-relative-time-format

A fully spec-compliant polyfill for 'Intl.RelativeTimeFormat'
TypeScript
12
star
14

intl-list-format

A fully spec-compliant polyfill for 'Intl.ListFormat'
TypeScript
11
star
15

CodeAnalyzer

A service that parses and reflects on the AST generated by Typescript's language service. With it, we can extract metadata such as initialization values and types, arguments and import declarations.
TypeScript
6
star
16

marshaller

A lightweight way to serialize and deserialize complex data types non-destructively
TypeScript
5
star
17

sass-extended-importer

A Custom Sass Import Resolver with included support for Node Module Resolution and additional file extensions
TypeScript
4
star
18

compatfactory

A library that unifies the TypeScript Compiler API factory functions across all versions of TypeScript and makes them conform with the Node Factory API
TypeScript
4
star
19

crosspath

A wrapper around the path module that always normalizes to POSIX (including converting backslashes to forward slashes)
TypeScript
2
star
20

node.parentelement

A spec-compliant cross-browser polyfill for Node.parentElement
JavaScript
2
star
21

EmojiChat

EmojiChat is a based on a simple concept: It tracks your and head position and facial expressions in real-time and puts an Emoji on top of your head that represents your current mood.
TypeScript
2
star
22

helpertypes

A collection of TypeScript helper types
TypeScript
2
star
23

notes

ITU notes
2
star
24

symboltable

A Generic Symbol Table implementation for JavaScript based on a Red-Black Binary Search Tree. Typed with Flow and exported as ES-modules.
JavaScript
2
star
25

es7-string-polyfills

Polyfills for String.prototype.padStart and String.prototype.padEnd
JavaScript
1
star
26

iterators-polyfill

Brings Iterators and Iterables to JavaScript for older browsers.
JavaScript
1
star
27

TypescriptASTUtil

A helper class for working with Typescript's AST
TypeScript
1
star
28

es6-string-polyfills

Polyfills for all new es6 string methods (except String.normalize).
JavaScript
1
star
29

TypescriptLanguageService

A host-implementation of Typescripts LanguageService.
TypeScript
1
star