# DI Container

FhyTS provides a lightweight and flexible Dependency Injection Container, allowing you to centrally and efficiently manage dependency instantiation and resolution.

## General Concepts

DI Containers allow you to:

* Register services using factory functions.
* Retrieve service instances safely and efficiently.
* Ensure each service is created only once (singleton pattern).

## API Reference

| Method | Type | Description |
| ------------------------ | ------------------------------------------- | ----------------------------------------------------- |
| `register(key, factory)` | `(key: string, factory: () => any) => void` | Registers a factory function for a given service. |
| `get(key)` | `<T>(key: string) => T` | Retrieves a service instance based on its key. |

## Usage Examples

#### Registration and Resolution

```javascript
import { DIContainer } from 'fhyts';
import { UserService } from './services/UserService';

const container = new DIContainer();

// Registration
container.register('userService', () => new UserService());

// Use
const userService = container.get<UserService>('userService');
await userService.getUsers();
```

#### With Chained Dependencies

If the service has other dependencies:

```javascript
container.register('userModel', () => new UserModel());
container.register('userService', () => {
  const model = container.get<UserModel>('userModel');
  return new UserService(model);
});
```

## Characteristics

* **Lazy Initialization**: Objects are only initialized the first time they are requested.
* **Singleton by default**: Each service is instantiated only once.
* **Factory-based**: Does not rely on reflection or metadata.

## Best Practices

* Use consistent and descriptive string keys (**userService**, **authService**, etc.).
* Register all services in one place (e.g., **container.ts**).
* Avoid creating instances directly outside the container, especially in large-scale applications.

## Next

Once you understand how to use DI Containers, you can move on to the [Config](#config) section to manage your application's configuration files in a flexible and structured way.