This package is a simple dependency injection container for JavaScript and TypeScript. It is inspired by the PHP Pimple package.
# NPM
npm install @davidcromianski-dev/ant-di
# PNPM
pnpm i @davidcromianski-dev/ant-di
The container is the main class of the package. It is used to store the services and parameters of the application.
import { Container } from '@davidcromianski-dev/ant-di';
const container = new Container();
To register services in the container, you can use the offsetSet method:
container.offsetSet('service', () => new Service());
To get services from the container, you can use the offsetGet method:
const service = container.offsetGet('service');
Note
If the service is a factory, it will be executed every time it is requested.
Caution
If the service is not in the container, an exception will be thrown.
To check if a service is registered in the container, you can use the offsetExists method:
const exists = container.offsetExists('service');
To remove services from the container, you can use the offsetUnset method:
container.offsetUnset('service');
To register factories in the container, you can use the factory method:
container.factory(() => new Service());
Tip
Useful for services that need to be created every time they are requested.
To protect services in the container, you can use the protect method:
container.protect(() => new Service());
Tip
By default, Ant DI assumes that any callable added to the container is a factory for a service, and it will invoke it when the key is accessed. The protected() method overrides this behavior, allowing you to store the callable itself.
To get raw values from the container, you can use the raw method:
const rawValue = container.raw('service');
Tip
Useful when you need access to the underlying value (such as a closure or callable) itself, rather than the result of its execution.
To get all keys registered in the container, you can use the keys method:
const keys = container.keys();
To register service providers in the container, you can use the register method:
import { Container, ServiceProviderInterface } from '@davidcromianski-dev/ant-di';
class MyServiceProvider implements ServiceProviderInterface {
register(container: Container) {
container.offsetSet('service', () => new Service());
return container;
}
}
container.register(new MyServiceProvider());
Tip
Useful for organizing the registration of services in the container.
This project is licensed under the MIT License. For more details, see the LICENSE file.