Coder Social home page Coder Social logo

smonn / container Goto Github PK

View Code? Open in Web Editor NEW
2.0 2.0 0.0 846 KB

Easy to use dependency injection container.

Home Page: https://www.npmjs.com/package/@smonn/container

License: MIT License

TypeScript 99.65% Shell 0.35%
nodejs dependency-injection javascript typescript

container's Introduction

@smonn/container

Dependency injection container. Attempts to avoid fixed dependencies via decorators. It also always returns the same instance unless you explicitly ask for a new instance. Instances are lazily created, meaning nothing is created until you request an instance. TypeScript optional, but attempts to infer types as much as possible.

Install

npm install @smonn/container
yarn add @smonn/container

Usage

Example usage. See more examples in the test files.

import { expect, test } from "vitest";
import { createContainer, createToken, IContainer } from "../src/index";

// Interfaces are optional, but can help to ensure you depend on abstractions only.
interface IGreeter {
  sayHello(): string;
}
interface IShouter {
  shoutHello(): string;
}

class Greeter implements IGreeter {
  // Can either define tokens along with the class implementation...
  static token = createToken<IGreeter>("greeter");

  constructor(private readonly name: string) {}

  sayHello(): string {
    return `Hello, ${this.name}!`;
  }
}

class Shouter implements IShouter {
  static token = createToken<IShouter>("shouter");

  constructor(private readonly greeter: IGreeter) {}

  shoutHello(): string {
    return this.greeter.sayHello().toUpperCase();
  }
}

class Other {
  ping() {
    return "pong";
  }
}

// Or define token types in a central location to help avoid circular imports.
const Tokens = {
  // Token type can also be inferred from the function signature
  name: createToken("name", String),

  // Or use explicit type and infer name from class
  other: createToken("other", Other),
} as const;

// Group together related classes in a single function to avoid a single
// massive function defining hundreds of dependencies. Also note that thanks to
// the token spec, explicitly declaring the generic type is not required.
function provideModule(container: IContainer) {
  // Literal/basic values are allowed
  container.set(Tokens.name, "Joy");
  container.set(Tokens.other, new Other());

  // Use factory functions to help resolve dependencies
  container.set(Greeter.token, (c) => new Greeter(c.get(Tokens.name)));
  container.set(Shouter.token, (c) => new Shouter(c.get(Greeter.token)));
}

const container = createContainer();
container.register(provideModule);

// Here shouter will have the correct type (the IShouter interface)
const shouter = container.get(Shouter.token);

test('returns "HELLO, JOY!"', () => {
  expect(shouter.shoutHello()).toBe("HELLO, JOY!");
});

test("always get the same instance", () => {
  expect(container.get(Shouter.token)).toBe(container.get(Shouter.token));
});

test("always get a new instance", () => {
  expect(container.create(Shouter.token)).not.toBe(
    container.create(Shouter.token)
  );
});

test("other will never create a new instance", () => {
  expect(container.create(Tokens.other)).toBe(container.create(Tokens.other));
});

container's People

Contributors

dependabot[bot] avatar smonn avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.