How to inject service in private constructor

1.3k views Asked by At

I have an existing code implementing singleton pattern by having private constructor and returning object instance returning the object -

export class SingletonFactory {
  private static factoryInstance = new SingletonFactory();

  private constructor() {
  }

  public static getInstance() {
    return SingletonFactory.factoryInstance;
  }
}

I need to inject a dependency into this factory. And I changed my code to the following -

@Inject('MyService')
export class SingletonFactory {
  private static factoryInstance = new SingletonFactory();

  private constructor(private myService : MyService) {
  }

  public static getInstance() {
    return SingletonFactory.factoryInstance;
  }
}

Please suggest, how I can inject the dependency at object creation in the constructor?

1

There are 1 answers

1
Kunvar Singh On

Inject into your component.

import { Router } from  '@angular/router';
    import { FormBuilder, FormGroup, Validators} from '@angular/forms';
    import { Location } from '@angular/common';
    constructor(public location: Location,public fb:FormBuilder,public global_service:GlobalService,public router: Router) { 

      }