Skip to content

Singleton Service - Single Instance Service

Singleton services that work with a single instance throughout the application.

🎯 What is it?

Singleton scope ensures that the service is created only once throughout the application and the same instance is used everywhere. It is the default scope type.

📦 Usage

typescript
import { xsingleton } from '@xcons/widget';

@xsingleton()
export class ConfigService {
  private config = { apiUrl: 'https://api.example.com' };

  getConfig() {
    return this.config;
  }
}

💡 When to Use?

  • Configuration: Application settings
  • State Management: Global state
  • Cache: Data caching
  • Logger: Logging service
  • API Client: HTTP client

📋 Examples

State Management

typescript
@xsingleton()
export class StateService {
  private state = new Map<string, any>();

  setState(key: string, value: any) {
    this.state.set(key, value);
  }

  getState(key: string) {
    return this.state.get(key);
  }
}

Cache Service

typescript
@xsingleton()
export class CacheService {
  private cache = new Map<string, any>();

  set(key: string, value: any) {
    this.cache.set(key, value);
  }

  get(key: string) {
    return this.cache.get(key);
  }

  clear() {
    this.cache.clear();
  }
}

HTTP Client

typescript
@xsingleton()
export class HttpClient {
  private baseUrl = 'https://api.example.com';

  async get<T>(endpoint: string): Promise<T> {
    const response = await fetch(`${this.baseUrl}${endpoint}`);
    return response.json();
  }

  async post<T>(endpoint: string, data: any): Promise<T> {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    return response.json();
  }
}

🔄 Lifecycle Hooks

typescript
import { xsingleton, OnServiceInit, OnServiceDestroy } from '@xcons/widget';

@xsingleton()
export class DatabaseService implements OnServiceInit, OnServiceDestroy {
  private connection: any;

  async onServiceInit() {
    this.connection = await this.connect();
  }

  async onServiceDestroy() {
    await this.connection?.close();
  }

  private async connect() {
    return { connected: true };
  }
}

📊 Behavior

typescript
@xsingleton()
class MyService {
  value = Math.random();
}

// Same instance everywhere
const service1 = injector.inject(MyService);
const service2 = injector.inject(MyService);

console.log(service1.value === service2.value); // true
console.log(service1 === service2); // true

✨ Summary

  • Single instance throughout the application
  • Default scope type
  • ✅ Ideal for state and cache
  • ✅ Memory efficient