Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ioc-service-container

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ioc-service-container

Lightweight ioc service container

  • 1.5.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
343
increased by174.4%
Maintainers
1
Weekly downloads
 
Created
Source

ioc-service-container

Quality Gate Status Bugs Code Smells Coverage Security Rating min-size min-size-g-zip dependency-count npm-version ts-types

This is a lightweight library for a service container written in TypeScript.

Buy Me A Coffee

Get started

Install the dependency with npm install ioc-service-container

Usage

First set up an Enum for preventing typos or redefinition of service ids in a file called ServiceIds.ts:

export enum ServiceId {
  TestApi = 'TestApi',
  TestService = 'TestService',
  FooApi = 'FooApi',
}

According to this you have to pass a factory of your required services to the ioc container. So at the initial script of your application you call a function named e.g. setupService:

import { ServiceContainer } from 'ioc-service-container';

function setupService() {
  ServiceContainer.set(ServiceId.TestApi, CustomTestApi); // setup by class reference
  ServiceContainer.set(ServiceId.FooApi, () => new CustomFooApi()); // setup by custom factory
  ServiceContainer.set(ServiceId.Xyz, () => 'xyz');
}

Now you have two options to inject the requested service. The first one is without the usage of TypeScript annotations. This can be used anywhere in your code:

Assign service to a var

import { scg, ServiceContainer } from 'ioc-service-container';

const testService = ServiceContainer.get<TestService>(ServiceId.TestService);
const testService1 = scg<TestService>(ServiceId.TestService); // scg is a shortcut for ServiceContainer.get()
Full TypeScript Support without generics

As you can see in the example above it's very unsexy to assign a service to a constant. You have to write 3 times testService (constant's name, generic & ServiceId). You are able to improve the typings by adding following content in your ServiceIds.ts file :

export enum ServiceId {
  TestApi = 'TestApi',
  // ...
}

declare module 'ioc-service-container' {
  export function scg<T extends keyof ServiceIdMap, U extends ServiceIdMap[T]>(id: T): U;

  type ServiceIdMap = {
    [ServiceId.TestApi]: TestApi,
  }
}

If you now use const a = scg(ServiceId.TestApi), a is correctly typed.

Inject service via typescript decorator

The second option is to use the @inject decorator inside a class:

export class CustomTestService implements TestService {
  @inject
  private readonly customApi!: Api; // Important is the naming of the property, its mapped to the serice id

  @inject(ServiceId.FooApi) // If you don't want to name your property like the service id, use this decorator
  private readonly nameThisHowYouWant!: Api;

  private readonly barApi = ServiceContainer.get<Api>(ServiceId.BarApi) // Use this syntax if you don't want to use decorators
}

Your can see a demo in the ./example folder. To run this type in npm run example.

Background

Structuring your code and avoiding implizit dependencies is two of the most effective ways to avoiding bugs, especially when code gets extended. To goal of Dependency Injection (DI) is to prevent structures like this:

class CustomService {
  constructor() {
    this.api = new CustomApi();
  }
}

The CustomService has an implizit dependency to the CustomApi.

Goal

The goal of DI is to encapsulate the dependencies of a class. The CustomService should work without knowing which api it is using. Following structure should be created:

+----------+    +-------------------+
|          |    |                   |
| Consumer +--->+ interface Service |
|          |    |                   |
+----------+    +---------+---------+
                          ^
                          |
                          |
                +---------+-----------+     +----------------+
                |                     |     |                |
                | class CustomService +---->+  interface Api |
                | implements Service  |     |                |
                |                     |     +--------+-------+
                +---------------------+              ^
                                                     |
                                                     |
                                            +--------+--------+
                                            |                 |
                                            | class CustomApi |
                                            | implements Api  |
                                            |                 |
                                            +-----------------+

(Btw asciiflow.com is a great tool for creating small charts for e.g. Readme.md)

Keywords

FAQs

Package last updated on 08 Nov 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc