magnodi
v1.1.7
Published
💉MagnoDI is a lightweight dependency injection package that simplifies managing dependencies in your projects, making them more scalable and maintainable.
Downloads
168
Maintainers
Readme
Features
- Lightweight
- Constructor based injection
- Property based injection
- Easy usage with TS decorators
Installation
Using npm:
npm install magnodi
Using yarn:
yarn add magnodi
Using pnpm:
pnpm add magnodi
You need to enable emitting decorator metadata in your Typescript config. Add these two lines to your tsconfig.json file under the compilerOptions key:
"emitDecoratorMetadata": true,
"experimentalDecorators": true
Constructor Based Injection
import { Container, Injectable } from 'magnodi'
@Injectable()
class ExampleInjectedService {
sayHi() {
console.log('Hi from injected service!')
}
}
@Injectable()
class ExampleService {
constructor(private injectedService: ExampleInjectedService) {}
greet() {
this.injectedService.sayHi()
}
}
const exampleService = Container.resolve<ExampleService>(ExampleService)
exampleService.greet()
// Output: 'Hi from injected service!'
Property Based Injection
import { Container, Injectable, Inject } from 'magnodi'
@Injectable()
class UserService {
private users = [{ id: 1, name: 'John Doe' }]
getUsers() {
return this.users
}
}
@Injectable()
class App {
@Inject()
private userService!: UserService
printUsers() {
const users = this.userService.getUsers()
console.log(users)
}
}
const app = Container.resolve<App>(App)
app.printUsers()
// Output: [{ id: 1, name: 'John Doe' }]
Contributing
- Fork this repository.
- Create a new branch with feature name.
- Create your feature.
- Commit and set commit message with feature name.
- Push your code to your fork repository.
- Create pull request.