DI framework - Nested service dependencies



Nested service dependencies

If a service is being used by a consumer be it a component or service then it need to know how to create that service. DI framework holds the responsibility to create and cache dependencies. The consumer just needs to notify the DI framework which dependencies it needs.

Service might depends on other services, which might even have nested dependency on yet other services. The dependency injection framework resolves these nested dependencies sequentially.

In the below snippet, LoggerService is common for both the component as well as the service.
at first in app.component.ts a instance of logger service is created.When product-context.service.ts requests from the DI framework its instance then the DI framework gives the same instance as it was already created and cached by the DI framework.

app.component.ts

constructor(logger: LoggerService, public productContext: ProductContextService) {
  productContext.Create(this.product);
  logger.logInfo('Product created');
}

product-context.service.ts

@Injectable({
  providedIn: 'root'
})
export class ProductContextService{
  constructor(private loggerService: LoggerService) {
  }
}

Comments