All Projects → artberri → diod

artberri / diod

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

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to diod

Ditranquillity
Dependency injection for iOS (Swift)
Stars: ✭ 317 (+780.56%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
Typhoon
Powerful dependency injection for Objective-C ✨✨ (https://PILGRIM.PH is the pure Swift successor to Typhoon!!)✨✨
Stars: ✭ 2,711 (+7430.56%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
Singularity
A extremely fast ioc container for high performance applications
Stars: ✭ 63 (+75%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
Container Ioc
Inversion of Control container & Dependency Injection for Javascript and Node.js apps powered by Typescript.
Stars: ✭ 89 (+147.22%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
waiter
Dependency injection, Inversion of control container for rust with compile time binding.
Stars: ✭ 71 (+97.22%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
stashbox
A lightweight, fast, and portable dependency injection framework for .NET-based solutions.
Stars: ✭ 120 (+233.33%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
vesselize
⛵ A JavaScript IoC container that works seamlessly with Vue.js and React.
Stars: ✭ 22 (-38.89%)
Mutual labels:  ioc, dependency-injection, inversion-of-control, di
CNeptune
CNeptune improve productivity & efficiency by urbanize .net module with meta-code to lay foundation for frameworks
Stars: ✭ 30 (-16.67%)
Mutual labels:  ioc, inversion-of-control, di
Ioc
🦄 lightweight (<1kb) inversion of control javascript library for dependency injection written in typescript
Stars: ✭ 171 (+375%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
di
🛠 A full-featured dependency injection container for go programming language.
Stars: ✭ 156 (+333.33%)
Mutual labels:  ioc, dependency-injection, di
DI-compiler
A Custom Transformer for Typescript that enables compile-time Dependency Injection
Stars: ✭ 62 (+72.22%)
Mutual labels:  ioc, dependency-injection, di
inject
[Archived] See https://github.com/goava/di.
Stars: ✭ 49 (+36.11%)
Mutual labels:  ioc, dependency-injection, di
ThunderboltIoc
One of the very first IoC frameworks for .Net that has no reflection. An IoC that casts its services before thunder casts its bolts.
Stars: ✭ 40 (+11.11%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
Qframework
Unity3D System Design Architecture
Stars: ✭ 2,326 (+6361.11%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
Hiboot
hiboot is a high performance web and cli application framework with dependency injection support
Stars: ✭ 150 (+316.67%)
Mutual labels:  ioc, dependency-injection, di
Typedi
Simple yet powerful dependency injection tool for JavaScript and TypeScript.
Stars: ✭ 2,832 (+7766.67%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
React Ioc
Hierarchical Dependency Injection with new React 16 Context API
Stars: ✭ 133 (+269.44%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
Go Spring
基于 IoC 的 Go 后端一站式开发框架 🚀
Stars: ✭ 744 (+1966.67%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
iocgo
A lightweight Inversion of Control (IoC) (Dependency Injection) container for Golang
Stars: ✭ 36 (+0%)
Mutual labels:  ioc, dependency-injection, inversion-of-control
awilix-express
Awilix helpers/middleware for Express
Stars: ✭ 100 (+177.78%)
Mutual labels:  dependency-injection, inversion-of-control, di

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 inabilty to emit Javascript constructs. DIOD autowiring will always be based on constructor typings and property injection will be avoided, even when it implies to work with abstract classes instead of interfaces.
  • I don't like to couple my domain or application layers (see hexagonal arquitecture) with a dependency injection library. Despite DIOD provides 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 with 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

Usage with Typescript

Modify your tsconfig.json to include the following settings

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

Add a polyfill for the Reflect API (example below use 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
// 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 arquitecture 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. 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 as 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[] {
    // ...
  }
}

More usage information in the official documentation.

Acknowledgements

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 realised 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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].