GithubHelp home page GithubHelp logo

artberri / diod Goto Github PK

View Code? Open in Web Editor NEW
124.0 8.0 3.0 742 KB

A very opinionated inversion of control (IoC) container and dependency injector for Typescript, Node.js or browser apps.

Home Page: https://www.npmjs.com/package/diod

License: MIT License

JavaScript 5.52% Shell 0.42% TypeScript 94.05%
di typescript inversion-of-control javascript dependency-injection ioc ts hacktoberfest

diod's Introduction

DIOD - Dependency Injection On Demand

DIOD - Dependency Injection On Demand

Rate on Openbase Contributor Covenant MIT license Build status codecov

About

A very opinionated and lightweight (under 2kB minified and gzipped) inversion of control container and dependency injector for Node.js or browser apps. It is available for vanilla Javascript usage but its true power will be shown by building Typescript apps.

Quick Start Guide | Documentation | Contributing

Motivation

💡 Do not want to waste your time on unnecessary documentation? Jump to the Quick Start Guide.

These are the reasons that have led me to reinvent the wheel and create DIOD:

  • I don't like the string-based solutions that current Typescript dependency injection libraries use to bypass the Typescript compiler's inability to emit Javascript constructs. DIOD autowiring will always be based on constructor typings and property injection will be avoided, even when it implies working with abstract classes instead of interfaces.
  • I don't like to couple my domain or application layers (see hexagonal architecture) with a dependency injection library. Despite DIOD providing a decorator for ease of usage, you are encouraged to create and use your own keeping your inner layers free of DIOD.

Both reasons are related to some TypeScript constraints: whenever you want to work with type information in runtime (in compiled JS), you inevitably need to use decorators. Even so, you won't be able to have information about interfaces at runtime.

It might sound ridiculous but Typescript needs types.

Read this article in my blog if you want more context about the reasons behind DIOD.

Features

  • Autowire
    When you ask for a service, DIOD reads the type-hints on your constructor and automatically passes the correct service dependencies to it. The same process will be used to create the required dependencies.
  • Custom decorators
    DIOD requires decorators for dependency guessing while autowiring, but it accepts any class decorator if you don't want to use the one it provides.
  • Compiler
    After all needed services are registered the container needs to be built. During this build, DIOD will check for errors like missing dependencies, wrong configurations, or circular dependencies. An immutable container will be finally created if there aren't any errors in the building.
  • Support for vanilla JS
    Usage with vanilla Javascript is possible by manually defining service dependencies.
  • Multiple containers
    It is possible to create multiple IoC containers.
  • Factory
    Using a factory to create services.
  • Instance
    Using a manually created instance to define a service.
  • Scope
    By default every service is transient, but they can be registered as singletons or as 'per request' (the same service instance will be used within a single request).
  • Visibility
    Services can be marked as private. Private services will be available only as dependencies and they will not be able to be queried from the IoC container.
  • Tagging
    Ability to tag services in the container and to query services based on tags.
  • Lightweight
    DIOD will be always dependency-free and under 2kB.

Quick Start Guide

Installation

npm install diod
# or
yarn add diod
# or
pnpm add diod

Usage with Typescript

Modify your tsconfig.json to include the following settings

{
	"compilerOptions": {
		"experimentalDecorators": true,
		"emitDecoratorMetadata": true
	}
}

Add a polyfill for the Reflect API (the example below uses reflect-metadata). You can use:

The Reflect polyfill import should be added only once in your code base and before DIOD is used:

npm install reflect-metadata
# or
yarn add reflect-metadata
# or
pnpm add reflect-metadata
// main.ts
import 'reflect-metadata'

// Your code here...

Basic usage

All the registered services must be decorated because this is the only way to make type metadata available at runtime in Typescript. DIOD provides the @Service() decorator for ease of usage, but you can create your own decorator to avoid coupling your inner architecture layers with DIOD.

Imagine that you want to have a class like this:

// application/use-cases/SignUpUseCase.ts
import { Service } from 'diod'

@Service()
export class SignUpUseCase {
	constructor(
		private readonly userRepository: UserRepository,
		private readonly mailer: Mailer,
	) {}

	execute(userData: UserDto): void {
		const user = this.userRepository.create(userData)
		this.mailer.sendConfirmationEmail(user)
	}
}

The D of the SOLID principles refers to dependency inversion. This principle encourages developers to use abstractions to define dependencies in certain situations. Abstractions are usually defined with interfaces in other languages, but Typescript interfaces are not available at runtime and that's why DIOD requires abstract classes for abstractions if you want them to be autowired. There is more information available in the Motivation section.

// application/services/Mailer.ts
export abstract class Mailer {
	sendConfirmationEmail(userData: user): void
	sendResetPasswordEmail(userData: user): void
}
// domain/UserRepository.ts
export abstract class UserRepository {
	create(userData: UserDto): User
	findBy(userData: UserCriteria): User[]
}

Finally, we need to create a configuration file where we will register every dependency of our app. This should be the only place where our dependencies will be coupled with a concrete implementation. We use to name this file diod.config.ts.

// infrastructure/diod.config.ts
import { ContainerBuilder } from 'diod'
// Other imports...

const builder = new ContainerBuilder()
builder.register(Mailer).use(AcmeMailer)
builder.register(UserRepository).use(SqliteUserRepository)
builder.registerAndUse(SignUpUseCase) // This is an alias of builder.register(SignUpUseCase).use(SignUpUseCase)
const container = builder.build()

const signUpUseCase = container.get(SignUpUseCase)
signUpUseCase.execute({
	/* ... */
})

The previous usage example assumes that you have some concrete implementations of the Mailer and the UserRepository abstractions. Note that abstract classes do not need to be extended and can be implemented just like an interface.

// infrastructure/AcmeMailer.ts
import { Service } from 'diod'
import { Mailer } from '../application/services/Mailer'

@Service()
export class AcmeMailer implements Mailer {
	sendConfirmationEmail(userData: user): void {
		// ...
	}
	sendResetPasswordEmail(userData: user): void {
		// ...
	}
}
// domain/SqliteUserRepository.ts
import { Service } from 'diod'
import { UserRepository } from '../domain/UserRepository'

@Service()
export class SqliteUserRepository implements UserRepository {
	create(userData: UserDto): User {
		// ...
	}
	findBy(userData: UserCriteria): User[] {
		// ...
	}
}

There is more useful information in the official documentation.

Acknowledgments

A special thanks to every open source contributor that helped or inspired me to create DIOD, including but not limited to all the contributors of the following libraries: InversifyJS, Node Dependency Injection, TSyringe, Autofac, Ninject and the Symfony DependencyInjection Component

Pronunciation and name origin

DIOD will be pronounced like the English word 'diode' /ˈdaɪəʊd/. DIOD is the abbreviation of Dependency Injection On Demand, which is the first I was able to elaborate after I realized that the short diod package name was free on the NPM registry.

License

DIOD is released under the MIT license:

MIT License

Copyright (c) 2021 Alberto Varela Sánchez

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

diod's People

Contributors

artberri avatar benoitlahoz avatar witrin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

diod's Issues

Unexpected error: TypeError: Cannot read property 'dependencies' of undefined if a direct dependency is missing other dependency

Describe the bug

When building the container if a service has a dependency registered with a missing dependency the Cannot read property 'dependencies' of undefined if a direct dependency is missing other dependency unexpected error is thrown.

To Reproduce

Run the test:

void tap.test(
  'throws error building a container with a registered service which has a dependency with unregistered dependencies',
  (t) => {
    // Arrange
    const builder = new ContainerBuilder()
    builder.register(Schedule).use(Schedule) // Schedule has Agenda as dependency
    builder.register(Agenda).use(Agenda) // Agenda has Clock as dependency but Clock is no registered

    // Assert
    t.throws(() => {
      // Act
      builder.build()
    }, new Error('Service not registered for the following dependencies of Agenda: Clock'))
    t.end()
  }
)

Expected behavior

Error Service not registered for the following dependencies of Agenda: Clock is thrown

Bug reported by @alemarcha

Update broken links from README.md

Broken Link 1

  • "create and use your own" link is not working:

1

  • The broken link is redirecting to a 404 - page not found:

2

Broken Link 2

  • "TypeScript needs types" link is not working:

3

  • The broken link is resulting in a "We can’t connect to the server at typescriptneedstypes.com." error:

4

Link to the PR

#14

Register same Service with different injections

Hi!

I have been looking for a way to define two implementations for the same service at the same time (For example, SendMailService) so that one of them injects the Logger implementation FakeLogger and another of them the implementation RealLogger) with the intention of being able to take one or the other depending on the needs. However, I think we cannot build the container with the same service in duplicate (The error is that the service identified as 'SendMailService' has already been registered and you would need to "unregister it before you can register it again"
The best solution I have found would be the following:

  // SendMailService.ts
  @Service()
  export class SendMailService {
   public constructor (private readonly logger: Logger) { }
  }

  // Service Register
  diodcontainer.registerFactoryAs(
    c => {
      return new SendMailService(
        env.realImplementation
          ? c.getDependency(RealLogger)
          : c.getDependency(FakeLogger),
      );
    },
    SendMailService,
    DependencyScope.Transient,
  );
  
  // SomeController.ts
  @Controller()
  export class SomeController {
  
    public async doStuffs(): Promise<void> {
      env.realImplementation = true; // or false
      const service = container.get(SendMailService);
      await service.send();
    }
  }

Do you think there could be a better solution or that the option of taking advantage of tags that allow a dual implementation to coexist could be introduced in the future?

Example:

  diodcontainer.registerFactoryAs(
    c => {
      return new SendMailService(c.getDependency(FakeLogger));
    },
    'SendMailServiceFakeLogger',
    DependencyScope.Transient,
  );

Example outputs "Service not decorated" Error

Hi, I tried to follow an example from the documentation but got Error: Service not decorated: ServiceOne. I could not figure out the problem.

I turned on the decorators support in tsconfig.jscon:

{
  "emitDecoratorMetadata": true,
   "experimentalDecorators": true,
}
import 'reflect-metadata';
import { ContainerBuilder, Service } from 'diod';

@Service()
export class ServiceOne {
  constructor(
    private readonly dep1: ServiceTwo,
    private readonly dep2: ServiceThree
  ) {}
}

@Service()
export class ServiceTwo {
  constructor(private readonly dep1: ServiceFour) {}
}

@Service()
export class ServiceThree {}

@Service()
export class ServiceFour {}

const builder = new ContainerBuilder();

builder.registerAndUse(ServiceOne);
builder.registerAndUse(ServiceTwo);
builder.registerAndUse(ServiceThree);
builder.registerAndUse(ServiceFour);

const container = builder.build();
const serviceOne = container.get(ServiceOne);
const serviceTwo = container.get(ServiceTwo);
const serviceThree = container.get(ServiceThree);
const serviceFour = container.get(ServiceFour);

console.log({ serviceOne, serviceTwo, serviceThree, serviceFour });

The error is:

throw new Error(`Service not decorated: ${[...parents, target.name].join(" -> ")}`);

Error: Service not decorated: ServiceOne
    at getDependenciesFromDecoratedServiceOrThrow 
    ...

Do you think automatic registration could be implemented?

It would be great to be able to automatically register all services that have the decorator.

As far as I know, it is not possible to do this because the meta-data is not generated without importing the classes, but maybe there is a way and I don't know it.

If you know any way in which we can approach this, I would like to collaborate with it. Just give me some clue and I'll start investigating.

Thanks.

Register after build?

I have a feature to inject a class in container, call it A, and then use is to initiate another class, call it B. The built container doesn't let me inject class B, it has to go through builder.

// Main.ts
this.#builder.registerAndUser(ClassA);
this.#container = this.#builder.build();
// Child.ts
const instanceA = this.#container.get(ClassA);

// main module doesn't know about class B
const instanceB: ClassB = createFromA(instanceA);

// the feature that I requested.
this.#container.register(ClassB).useInstance(instanceB);
this.#container.rebuild();

I wonder if I need to rebuild or we should let user inject directly to Container?

Circular dependency detection expects unique class names

Given classes with the same name leads falsely to Error: Circular dependency detected: [...] during build:

To Reproduce

// module foo/bar
export class A {
}
// module foo/baz
export class A {
}
// module foo/index
export * as bar from './bar';
export * as baz from './baz';
// module qux
import foo from './foo';

export class B {

  constructor( x, y ) {
    // ...
  }
}
// module bootstrap
import '@abraham/reflection';
import { ContainerBuilder } from 'diod';
import foo from './foo';
import qux from './qux';
// [...]
const builder = new ContainerBuilder();

builder.register(foo.bar.A).useClass(foo.bar.A);
builder.register(foo.baz.A).useClass(foo.baz.A);
builder.use(qux.B).useClass(qux.B).withDependencies([foo.bar.A, foo.baz.A]);

builder.build();

Expected behavior
Duplicate class names do not lead to false circular dependency errors.

Unregister service / replace implementation

Hello and thank you very much for this library!

I'm currently working on a Vue.js plugin to integrate DIOD in Vue.

It's a work in progress and I'm learning to use DIOD, but you can find it here and a first documentation with examples there.

I was wondering if it would be possible to unregister dependencies for a 'cleaning' purpose , e.g. in case of crash or simply when quitting application (tab close, Electron quit, ...). Generally speaking I'm asking myself if the container(s) need to be teared down to be garbage collected, how it is done or how it could be done.

I guess the possibility to 'unregister' services or to replace implementations at runtime would provide a simple way to use feature toggles too...

I hope my question is clear... 🙃

Thank you very much.

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.