Skip to main content

Classes

Injecting classes

Injecting classes is a two step process. First, annotate the class with the @Injectable annotation and pass the graph from which dependencies should be resolve. Then, declare the dependencies as class members and annotate them with the @Inject annotation.

import {Injectable, Inject} from 'react-obsidian';
import {ApplicationGraph} from './ApplicationGraph';

@Injectable(ApplicationGraph)
export class MyClass {
@Inject() private httpClient!: HttpClient;

}
Always prefer constructor injection over field injection

Constructor injection is the preferred way to inject dependencies. It is more explicit and easier to test. Field injection should only be used when a class is not instantiated by a graph.

Delayed injection

Dependencies annotated with the @Inject annotation are resolved immediately after the constructor is called. If you want to inject a class at a later point in time, you can use the @LateInject annotation instead, and inject the dependencies by manually with the Obsidian.inject() function.

import {Injectable, LateInject} from 'react-obsidian';
import {ApplicationGraph} from './ApplicationGraph';

@Injectable(ApplicationGraph)
export class MyClass {
@LateInject() private httpClient!: HttpClient;

public init() {
console.log(this.httpClient === undefined); // true
Obsidian.inject(this);
console.log(this.httpClient === undefined); // false
}
}