title: How to access DI from model in a generic way?
body: <p>I have the following class (only the relevant part):</p>
  
  <pre><code>import { AppInjector } from '@app/shared/utility/app-injector';
  import { HttpService } from '@app/shared/services/http.service';
  
  export class Lazy&lt;T&gt; {
  
      private readonly _http: HttpService = AppInjector.get(HttpService);
  
      private _init() {
          // Usage of this._http
      }
  }
  </code></pre>
  
  <p>So basically, this is a simple type but that needs to use the Angular <code>HttpService</code>.
  To do so, I created a file with the following code:</p>
  
  <pre><code>import { Injector } from '@angular/core';
  
  export let AppInjector: Injector;
  
  export function setAppInjector(injector: Injector) {
      if (AppInjector) {
          console.error('Programming error: AppInjector was already set');
      }
      else {
          AppInjector = injector;
      }
  }
  </code></pre>
  
  <p>And I'm setting it in the constructor of my <code>AppModule</code>:</p>
  
  <pre><code>export class AppModule {
      constructor(injector: Injector) {
          setAppInjector(injector);
      }
  }
  </code></pre>
  
  <p>Finally, I use it for example in a service:</p>
  
  <pre><code>@Injectable({
      providedIn: 'root',
  })
  export class FooService {
  
      private readonly ROUTE: string = "/api/foo";
  
      private _campaigns: Lazy&lt;ICampaign[]&gt; = new Lazy&lt;ICampaign[]&gt;(`${this.ROUTE}/campaigns`);
  
      public get campaigns(): Lazy&lt;ICampaign[]&gt; {
          return this._campaigns;
      }
  }
  </code></pre>
  
  <p>And in a component, I can do something like:</p>
  
  <pre><code>export class FooComponent implements OnInit {
      constructor(private _fooService: FooService) {}
  
      public async ngOnInit(): Promise&lt;void&gt; {
          await this._fooService.campaigns.load();
      }
  }
  </code></pre>
  
  <p>This works pretty well but I'm wondering how I could make this more generic.
  Indeed, say I wanted to create a separate npm package with just this class, I can't tell users to create the <code>setAppInjector</code> function and to register it in the <code>AppModule</code> (and I could not even use it from my npm package anyway...).</p>
  
  <p>So I'm searching for an Angular way to make this generic, something like passing something in the <code>providers</code> property of the decorator of the <code>AppModule</code>.</p>
  
  <p>Any idea?</p>