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.
- 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.
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
// 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);
// user.controller.js
import { ioc } from '@andrew_l/ioc';
export function createUser() {
const UserService = ioc('UserService');
ctx.body = await UserService.create(ctx.request.body);
}
- 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.