The injection context is related to the concept of Angular dependency injection
What is the injection context?
It is a runtime environment where Angular determines which instance of a dependency should be provided when something requests it
It is a place where the dependent injection looks up and resolves the dependencies when requested by a component, directive, or service
inject Method
With dependency injection, we use the constructors to inject the required service into a component, directive, or service
simple example of Dependency Injection
constructor(private http:HttpClient){}
This can be simplified using the latest inject method available in the latest versions of Angular
simple example of an inject function
const http = inject(HttpClient);
Importance of Injection Context
When we need any service to be injected anywhere inside the component or directive, the injection context plays a major role in resolving these dependencies
In general, inside a service file, we will write
@Injectable(providedIn : 'root' )
And at the component level, we will write it in the providers array
And in the latest Angular versions, we can use the inject method outside the constructor as well
So, for all these injection contexts, ensure that the requested services are injected at the requested hierarchy only(i.e, component level, root level)
If Angular cannot find the service, then it looks for its parent injectors until it finds a provider or throws an error. The injection context helps in navigating this hierarchy
Availability of Injection context
The injection context is available in the constructors of components, services, and directives as well
class Demo{
userService = inject(UserService); //Injection context available
constructor(private http:HttpClient) //Injection context available
{
this.demoService = inject(DemoService); //Injection context available
}
}
It is also available in the factory functions for providers
providers : [
{
provide: Some_Token,
useFactory: () => {
const httpClient = inject(HttpClient) //Injection context available
return new ClassName(httpClient);
}
}
]
Running the inject function outside the automatically provided contexts
We can use the runInjectionContext method here
import {inject, EnvironmentInjector, runInjectionContext} from '@angular/core';
class Demo{
constructor(private injector:EnvironmentInjector){}
someMethod(){
runInjectionContext(this.injector, ()=>{
const myService = inject(MyService); //works here
}
}
}
*Summary *
The injection context allows Angular dependency injection to function properly. It defines the scope where Angular can look up and provide the dependencies that are requested by components, services, and directives.
Thankyou...
Happy Coding...
Top comments (0)