title: NestJs: Dynamically Create Instances of Class
body: <p>Instead of Singletons, I want to create dynamically class instances in NestJs. </p>
  
  <p>I found two ways:</p>
  
  <h3>1) Directly create the class (ChripSensor is then not @Injectable)</h3>
  
  <pre><code>import { ChirpSensor } from './chirp-sensor/chirp-sensor';
  
  @Injectable()
  export class SensorsService {
    registeredSensors: any;
    constructor(
      @InjectModel('Sensor') private readonly sensorModel: Model&lt;ISensor&gt;,
      private i2cService: I2cService) {
         const sensors = this.i2cService.getSensors();
         sensors.forEach((sensor) =&gt; {this.registeredSensors[sensor._id] = new ChirpSensor({name: sensor.name})});
  
      }
  </code></pre>
  
  <p>I'm wondering if that is consistent with the DI way of nest.js</p>
  
  <h3>2) The second solution would be via a <a href="https://docs.nestjs.com/fundamentals/custom-providers" rel="nofollow noreferrer">factory</a>, but here I don't know how to pass the options.</h3>
  
  <pre><code>export const chirpFactory = {
    provide: 'CHIRP_SENSOR',
    useFactory: (options) =&gt; {
      console.log('USING FACTORY CHIRP, options', options)
      if (process.env.SIMULATION === 'true') {
        return new ChirpSensorMock(options);
      }
      else {
        return new ChirpSensor(options);
      }
    }
  };
  </code></pre>
  
  <p>Not quite sure how to continue here/ inject the factory properly as the examples create the object in the constructor without options? </p>
  
  <h2>Question:</h2>
  
  <p>What is the <code>NestJs</code> way to create those class instances?</p>
  
  <h1>Edit - for B12Toastr</h1>
  
  <h3>Module - get the Mock or Original on Compile time</h3>
  
  <pre><code>providers: [
    {
      provide: 'CHIRP_SENSOR',
      useValue: process.env.SIMULATION === 'true'
        ? ChirpSensorMock
        : ChirpSensor
    },
  ],
  </code></pre>
  
  <h3>Sensor Service</h3>
  
  <pre><code>@Injectable()
  export class SensorsService {
    registeredSensors: any;
    constructor(
      @Inject('CHIRP_SENSOR') private ChirpSensorClass: any, // any works but ChirpSensorMock | ChirpSensor not
      private i2cService: I2cService
     ) {
      const sensors = this.i2cService.getSensors();
      sensors.forEach((sensor) =&gt; {this.registeredSensors[sensor._id] = new ChirpSensorClass({name: sensor.name})});
  
    }
  </code></pre>