Inversion of Control (IoC) Toolkit
A simple and flexible Inversion of Control (IoC) container to help set up and manage services in your application. This toolkit automates the process of importing and registering services, ensuring that dependencies are injected properly before running your application code.
🔧 Installation
sh
$ npm add -D @andrew_l/ioc
sh
$ pnpm add -D @andrew_l/ioc
sh
$ yarn add -D @andrew_l/ioc
✨ Features
- Service Container: Centralized place for managing service instances and dependencies.
- Automatic Import: Auto-imports
*.service.js
files from the specified directories for service registration. - TypeScript Support: Generates types for services for better developer experience in TypeScript.
- Flexible Setup: Easily configure paths, patterns, and output types for IoC setup.
🚀 Setup Example
js
import { ServiceContainer } from '@andrew_l/ioc';
await ServiceContainer.setup({
pathRoot: process.cwd(), // Root directory of your services
autoImportPatterns: ['./services/*/**/*.service.{js,mjs}'], // Pattern to automatically import service files
typeOutput: './ioc.d.ts', // Path to output generated types
generateTypes: true, // Enable type generation for TypeScript
});
// Your application code follows
🚀 Usage Example
Service Definition
js
// user.service.js
import { ServiceContainer } from '@andrew_l/ioc';
export class UserService {
async create() {
// Service logic for creating a user
// TODO: Implement the user creation logic
}
}
// Register the UserService in the container
ServiceContainer.set('UserService', UserService);
Controller Using IoC
js
// user.controller.js
import { ioc } from '@andrew_l/ioc';
export function createUser() {
const UserService = ioc('UserService');
ctx.body = await UserService.create(ctx.request.body);
}
🤔 Why Use This Package?
- Centralized Service Management: Automatically manage and resolve service dependencies, making it easier to organize and scale your application.
- Auto-import Services: Automatically imports services from your specified directory, reducing boilerplate and manual imports.
- Flexible and Customizable: Easily configure paths and types, making it adaptable to various project structures.
- Improved Developer Experience: Supports TypeScript for type generation.