/DI

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

Primary LanguageTypeScriptMIT LicenseMIT

Modifications to the original in this fork

This fork has been made to manage changes necessary to use with an embedded JavaScript framework called ModdableSDK. There are five main changes:

  1. Addition of a ttypescript module to allow for compiling with the command ttsc using the required DI transformer. Also updated package.json to use a postinstall script to load the required modules.
  2. Addition of a new singleton for DIContainer as static member DIContainer.container(). Primary intended use is for libraries where the library wishes to be consumable from code that might not use or instantiate DIContainer. By having the library import code define the injections using the shared singleton instance, the library can operate stand-alone, while still working with other libraries or main application that consumes DIContainer.
  3. Addition of a manifest.json file required by Moddable to control the build. This file is similar to a package.json file used by Node, but has a different format and technique to include files.
  4. A change to di-container.ts to resolve a typescript error due to a missing cast.
  5. Remove dist from .gitignore so that we can check in the typescript compiled files. This is a bit of a hack, as we should publish a package. Hopefully once this is resolved the changes can be pulled into wessberg/di to avoid all of this!
  6. Improved some error handling, with better hints when the transformer isn't working and constructor exceptions now throw the original error rather than one that is likely less descriptive.

Using this requires changing the typescript compiler from tsc to ttsc in the Moddable manifest.json file, and setting up the TypeScript to use the di tranformer. This is done by adding the following to manifest.json:

  "typescript": {
    "compiler": "ttsc",
    "tsconfig": {
      "compilerOptions": {
        "plugins": [
          {
            "transform": "$(PROJECT_DIR)/node_modules/@cmidgley/di/ttypescript/src/transformer.js"
          }
        ]
      }
    }
  }

Don't forget to add this package to your package.json file, such as:

"dependencies": {
  "@cmidgley/di": "https://github.com/cmidgley/di"
}

Original README

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
Bubbles
Twitter: @usebubbles
Christopher Blanchard Ideal Postcodes Xerox Trent Raymond

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)