nicojs / typed-inject

Type safe dependency injection for TypeScript
Apache License 2.0
448 stars 23 forks source link

Question: Circular Dependencies #46

Open snnsnn opened 2 years ago

snnsnn commented 2 years ago

Please can you address how to handle circular dependencies, with an example if possible.

nicojs commented 2 years ago

You mean something like this?

import { createInjector } from "typed-inject";

class HttpClient {
  public static inject = ["logger"] as const;
  public service?: MyService;
}

class MyService {
  constructor(private http: HttpClient) {
    http.service = this; // Assign circular dependency
  }
  public static inject = ["httpClient"] as const;
}

const appInjector = createInjector().provideClass("httpClient", HttpClient);

const myService = appInjector.injectClass(MyService);

If not, please try to explain with a code example.

snnsnn commented 2 years ago

@nicojs I was asking for something more like a direct dependency between two services, or dependency through a third service.

A -> B -> A A -> B -> C -> A

I don't have a concrete example at the moment, just trying to assess potentials of different IOC libraries.