{"id":17035722,"url":"https://github.com/artberri/diod","last_synced_at":"2025-04-09T10:00:49.141Z","repository":{"id":47489883,"uuid":"365047482","full_name":"artberri/diod","owner":"artberri","description":"A very opinionated inversion of control (IoC) container and dependency injector for Typescript, Node.js or browser apps. ","archived":false,"fork":false,"pushed_at":"2024-10-04T14:56:34.000Z","size":982,"stargazers_count":143,"open_issues_count":0,"forks_count":4,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-04-02T08:01:44.656Z","etag":null,"topics":["dependency-injection","di","hacktoberfest","inversion-of-control","ioc","javascript","ts","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/diod","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/artberri.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-05-06T22:02:22.000Z","updated_at":"2025-03-10T12:42:26.000Z","dependencies_parsed_at":"2024-06-11T21:45:39.682Z","dependency_job_id":"25423283-8af9-4c38-a556-1121778a677d","html_url":"https://github.com/artberri/diod","commit_stats":{"total_commits":59,"total_committers":4,"mean_commits":14.75,"dds":0.1694915254237288,"last_synced_commit":"5d471666e801210a3e6e73976fdbd98eb7158aca"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/artberri%2Fdiod","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/artberri%2Fdiod/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/artberri%2Fdiod/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/artberri%2Fdiod/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/artberri","download_url":"https://codeload.github.com/artberri/diod/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248018032,"owners_count":21034045,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-injection","di","hacktoberfest","inversion-of-control","ioc","javascript","ts","typescript"],"created_at":"2024-10-14T08:47:53.317Z","updated_at":"2025-04-09T10:00:49.033Z","avatar_url":"https://github.com/artberri.png","language":"TypeScript","funding_links":[],"categories":["Built with TypeScript"],"sub_categories":["Libraries"],"readme":"# DIOD - Dependency Injection On Demand\n\n![DIOD - Dependency Injection On Demand](https://raw.githubusercontent.com/artberri/diod/main/cover.jpg)\n\n[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](./CODE_OF_CONDUCT.md)\n[![MIT license](https://img.shields.io/npm/l/diod)](./LICENSE)\n[![Build status](https://github.com/artberri/diod/actions/workflows/qa.yml/badge.svg)](https://github.com/artberri/diod/actions)\n[![codecov](https://codecov.io/gh/artberri/diod/branch/main/graph/badge.svg?token=AGYQWMUQCA)](https://codecov.io/gh/artberri/diod)\n\n## About\n\nA 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.\n\n[Quick Start Guide](#quick-start-guide) |\n[Documentation](./docs/README.md) |\n[Contributing](./CONTRIBUTING.md)\n\n### Motivation\n\n\u003e 💡 Do not want to waste your time on unnecessary documentation? Jump to the [Quick Start Guide](#quick-start-guide).\n\nThese are the reasons that have led me to reinvent the wheel and create DIOD:\n\n- 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.\n- I don't like to couple my domain or application layers (see [hexagonal architecture](\u003chttps://en.wikipedia.org/wiki/Hexagonal_architecture_(software)\u003e)) with a dependency injection library. Despite DIOD providing a decorator for ease of usage, you are encouraged to [create and use your own](./docs/custom-decorator.md) keeping your inner layers free of DIOD.\n\nBoth 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.\n\nIt might sound ridiculous but [Typescript needs types](https://github.com/akutruff/typescript-needs-types).\n\nRead [this article in my blog](https://www.albertovarela.net/blog/2021/06/diod-dependency-injection-typescript/) if you want more context about the reasons behind DIOD.\n\n### Features\n\n- **Autowire**  \n  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.\n- **Custom decorators**  \n  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.\n- **Compiler**  \n  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.\n- **Support for vanilla JS**  \n  Usage with vanilla Javascript is possible by manually defining service dependencies.\n- **Multiple containers**  \n  It is possible to create multiple IoC containers.\n- **Factory**  \n  Using a factory to create services.\n- **Instance**  \n  Using a manually created instance to define a service.\n- **Scope**  \n  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).\n- **Visibility**  \n  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.\n- **Tagging**  \n  Ability to tag services in the container and to query services based on tags.\n- **Lightweight**  \n  DIOD will be always dependency-free and under 2kB.\n- **Automatic registration**  \n  It is not included by default but it can be achieved easily, check the [documentation](./docs/automatic-registration.md).\n\n## Quick Start Guide\n\n### Installation\n\n```sh\nnpm install diod\n# or\nyarn add diod\n# or\npnpm add diod\n```\n\n#### Usage with Typescript\n\nModify your `tsconfig.json` to include the following settings\n\n```json\n{\n\t\"compilerOptions\": {\n\t\t\"experimentalDecorators\": true,\n\t\t\"emitDecoratorMetadata\": true\n\t}\n}\n```\n\nAdd a polyfill for the Reflect API (the example below uses `reflect-metadata`). You can use:\n\n- [reflect-metadata](https://www.npmjs.com/package/reflect-metadata)\n- [core-js (core-js/es7/reflect)](https://www.npmjs.com/package/core-js)\n- [reflection](https://www.npmjs.com/package/@abraham/reflection)\n\nThe Reflect polyfill import should be added only once in your code base and before DIOD is used:\n\n```sh\nnpm install reflect-metadata\n# or\nyarn add reflect-metadata\n# or\npnpm add reflect-metadata\n```\n\n```ts\n// main.ts\nimport 'reflect-metadata'\n\n// Your code here...\n```\n\n### Basic usage\n\nAll the registered services must be decorated because [this is the only way to make type metadata available at runtime](https://www.typescriptlang.org/tsconfig#emitDecoratorMetadata) in Typescript. DIOD provides the `@Service()` decorator for ease of usage, but you can [create your own decorator](./docs/custom-decorator.md) to avoid coupling your inner architecture layers with DIOD.\n\nImagine that you want to have a class like this:\n\n```ts\n// application/use-cases/SignUpUseCase.ts\nimport { Service } from 'diod'\n\n@Service()\nexport class SignUpUseCase {\n\tconstructor(\n\t\tprivate readonly userRepository: UserRepository,\n\t\tprivate readonly mailer: Mailer,\n\t) {}\n\n\texecute(userData: UserDto): void {\n\t\tconst user = this.userRepository.create(userData)\n\t\tthis.mailer.sendConfirmationEmail(user)\n\t}\n}\n```\n\nThe **D** of the [SOLID](https://en.wikipedia.org/wiki/SOLID) principles refers to [dependency inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle). 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](#motivation) section.\n\n```ts\n// application/services/Mailer.ts\nexport abstract class Mailer {\n\tsendConfirmationEmail(userData: user): void\n\tsendResetPasswordEmail(userData: user): void\n}\n```\n\n```ts\n// domain/UserRepository.ts\nexport abstract class UserRepository {\n\tcreate(userData: UserDto): User\n\tfindBy(userData: UserCriteria): User[]\n}\n```\n\nFinally, 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`.\n\n```ts\n// infrastructure/diod.config.ts\nimport { ContainerBuilder } from 'diod'\n// Other imports...\n\nconst builder = new ContainerBuilder()\nbuilder.register(Mailer).use(AcmeMailer)\nbuilder.register(UserRepository).use(SqliteUserRepository)\nbuilder.registerAndUse(SignUpUseCase) // This is an alias of builder.register(SignUpUseCase).use(SignUpUseCase)\nconst container = builder.build()\n\nconst signUpUseCase = container.get(SignUpUseCase)\nsignUpUseCase.execute({\n\t/* ... */\n})\n```\n\nThe 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._\n\n```ts\n// infrastructure/AcmeMailer.ts\nimport { Service } from 'diod'\nimport { Mailer } from '../application/services/Mailer'\n\n@Service()\nexport class AcmeMailer implements Mailer {\n\tsendConfirmationEmail(userData: user): void {\n\t\t// ...\n\t}\n\tsendResetPasswordEmail(userData: user): void {\n\t\t// ...\n\t}\n}\n```\n\n```ts\n// domain/SqliteUserRepository.ts\nimport { Service } from 'diod'\nimport { UserRepository } from '../domain/UserRepository'\n\n@Service()\nexport class SqliteUserRepository implements UserRepository {\n\tcreate(userData: UserDto): User {\n\t\t// ...\n\t}\n\tfindBy(userData: UserCriteria): User[] {\n\t\t// ...\n\t}\n}\n```\n\nThere is more useful information in the [official documentation](./docs/README.md).\n\n## Acknowledgments\n\nA 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](https://github.com/inversify/InversifyJS), [Node Dependency Injection](https://github.com/zazoomauro/node-dependency-injection), [TSyringe](https://github.com/microsoft/tsyringe), [Autofac](https://github.com/autofac/Autofac), [Ninject](https://github.com/ninject/Ninject) and the [Symfony DependencyInjection Component](https://github.com/symfony/dependency-injection)\n\n## Pronunciation and name origin\n\nDIOD 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.\n\n## License\n\nDIOD is released under the MIT license:\n\nMIT License\n\nCopyright (c) 2021 Alberto Varela Sánchez\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fartberri%2Fdiod","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fartberri%2Fdiod","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fartberri%2Fdiod/lists"}