1

I'm from .NET background, just a question on Dependency Injection in Angular.

In .NET/.NET Core, there are three different service lifetimes which are: Transient, Scoped and Singleton. But for Angular, it only has equivalent "Singleton", is my understanding correct? If yes, why Angular not provide other service type like "Transient"?

1 Answer 1

4

Technically, all services in Angular are scoped. However, they can be scoped to:

  1. Root - an instance of a service provided in the root (or injected in AppModule) is shared between all modules and components. This is also what we call a singleton, scoped to root (entire app).
@Injectable({
  providedIn: 'root',
})
  1. Module - an instance of a service provided in a lazy-loaded module is shared between the components of the module. This is also a singleton, but scoped to a module.
@NgModule({
  ...
  providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
  1. Component - an instance of a service injected into a component only lives while that component lives. Once that component is destroyed, the instance o the service is also destroyed. Multiple instances of the same component each have their own instance of the service.
@Component({
  ...
  providers: [{ provide: ItemService, useValue: { name: 'lamp' } }]
})

This section of the documentation touches upon the hierarchy of injection: https://angular.io/guide/hierarchical-dependency-injection

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.