Skip to content

Transient Service - New Instance Every Time

Transient services that create a new instance on every use.

🎯 What is it?

Transient scope ensures that a new instance of the service is created every time it is requested. No caching is done.

📦 Usage

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

@xtransient()
export class LoggerService {
  private id = Math.random();

  log(message: string) {
    console.log(`[${this.id}] ${message}`);
  }
}

💡 When to Use?

  • Stateless Operations: Operations without state
  • Independent Tasks: Each operation should be independent
  • Temporary Objects: Short-lived objects
  • Task Executor: New executor for each task

📋 Examples

Logger Service

typescript
@xtransient()
export class RequestLogger {
  private requestId = Date.now();

  logRequest(method: string, url: string) {
    console.log(`[${this.requestId}] ${method} ${url}`);
  }

  logResponse(status: number) {
    console.log(`[${this.requestId}] Response: ${status}`);
  }
}

Validator

typescript
@xtransient()
export class DataValidator {
  private errors: string[] = [];

  validate(data: any) {
    if (!data.email) this.errors.push('Email required');
    if (!data.name) this.errors.push('Name required');
    
    return this.errors.length === 0;
  }

  getErrors() {
    return this.errors;
  }
}

Task Processor

typescript
@xtransient()
export class TaskProcessor {
  private taskId = `task-${Date.now()}`;

  async process(data: any) {
    console.log(`${this.taskId} started`);
    
    // Do the work
    await this.doWork(data);
    
    console.log(`${this.taskId} completed`);
  }

  private async doWork(data: any) {
    // Processing logic
  }
}

Command Handler

typescript
@xtransient()
export class CommandHandler {
  private context = { userId: null, timestamp: Date.now() };

  setContext(userId: string) {
    this.context.userId = userId;
  }

  execute(command: string) {
    console.log('Executing:', command, this.context);
  }
}

📊 Behavior

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

// Different instance every time
const service1 = injector.inject(MyService);
const service2 = injector.inject(MyService);

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

🔄 Lifecycle Hooks

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

@xtransient()
export class TempService implements OnServiceInit, OnServiceDestroy {
  onServiceInit() {
    console.log('New instance created');
  }

  onServiceDestroy() {
    console.log('Instance being cleaned up');
  }
}

⚠️ Things to Consider

  • A new instance is created on every injection
  • No caching, higher memory usage
  • State is not shared
  • Lifecycle hooks run for each instance

✨ Summary

  • New instance on every use
  • No caching
  • ✅ Ideal for stateless operations
  • ✅ Suitable for independent tasks