A special thanks to Symfony which was a great inspiration and example for this project.
The Node Dependency Injection component allows you to standardize and centralize the way objects are constructed in your application.
npm install --save node-dependency-injection
Imagine you have a Mailer
class like this:
// services/Mailer.js
export default class Mailer {
/**
* @param {ExampleService} exampleService
*/
constructor(exampleService) {
this._exampleService = exampleService;
}
...
}
You can register this in the container as a service:
import {ContainerBuilder} from 'node-dependency-injection'
import Mailer from './services/Mailer'
import ExampleService from './services/ExampleService'
let container = new ContainerBuilder()
container
.register('service.example', ExampleService)
container
.register('service.mailer', Mailer)
.addArgument('service.example')
And get services from your container
const mailer = container.get('service.mailer')
You can also use configuration files to improve your service configuration
# /path/to/file.yml
services:
service.example:
class: 'services/ExampleService'
service.mailer:
class: 'services/Mailer'
arguments: ['@service.example']
import {ContainerBuilder, YamlFileLoader} from 'node-dependency-injection'
let container = new ContainerBuilder()
let loader = new YamlFileLoader(container)
loader.load('/path/to/file.yml')
And get services from your container easily
...
const mailer = container.get('service.mailer')
- Configuration files with JS, YAML or JSON.
- Multiple configuration files
- Custom relative service directory
- Compiling container
- Custom compiler pass
- Change definition behaviour
- Using a factory to create services
- Nullable Dependencies
- Public or private services
- Service Aliasing
- Service Tagging
- Parameters Injection
- Lazy Services
- Deprecate Services
- Decorate Services
- Synthetic Services
- Non Shared Services
- Parent and Abstract Services
- Custom Logger
- Container as Service
Please read full documentation
If you are using expressJS and you like Node Dependency Injection Framework then I strongly recommend
you to use the node-dependency-injection-express-middleware
package.
That gives you the possibility to retrieve the container from the request.
npm install --save node-dependency-injection-express-middleware
import NDIMiddleware from 'node-dependency-injection-express-middleware'
import express from 'express'
const app = express()
const options = {serviceFilePath: 'some/path/to/config.yml'}
app.use(new NDIMiddleware(options).middleware())