Dependency Injection Flashcards

1
Q

What is Dependency Injection?

A
  • It is an important application design pattern.
  • This increases the efficiency and modularity.
  • They are services or objects that a class needs to perform its function.
  • It is a coding pattern in which a class asks for dependencies from external sources rather than creating them itself.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

@Injectable decorator

A

@Injectable({ providedIn: ‘root’ })

export class xyzService{

getXyz() { return abc; }

}

  • The class is a service.
  • The injectable decorator markts it as a service that can be injected.
  • The injector is responsible for creating service instances and injecting them into classes.
  • A provider tells an injector how to create the service.
  • Injector has to be configured in the provider.
  • It can be configured at different levels
    • @Injectable() decorator
    • @NgModule() decorator
    • @Component() decorator
  • When generating services, it is adding extra metadata with a ‘provided in’ property with a default of ‘root’ (it can be any module of the application)
  • If ‘root’ is used then injectable will be registered as a singleton in the application and it is not needed to be added to the providers of the root module.
  • If ‘UserModule’ is used then the injectable is registered as a provider of the userModule without adding it to the providers in the module.
  • The better option is to provide it in @NgModule() - otherwise it will be plauged with circular dependencies.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Configure injectors

A
  1. By using providedIn metadata option - with root injector or the injector for a specific NgModule. @Injectable({ providedIn:’root’}) – provides this service in the root
  2. The @NgModule() and @Component() decorators have the providers metadata option, where you can configure providers for NgModule-level or component-level injectors. @Component({ providers: [{provide: abcService, useValue: { name:’lmp’} }] }) —This is visible only at component.
  3. @NgModule()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Injector hierarchy

A

There is only one root injector for an app.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly