Mandarine.TS
Search…
Accessing DI container
This page summarizes how to get a injectable object from the DI Container programatically.

Concepts

    Resolved component
      A component that has been initialized by the DI Factory, and all dependencies in it are ready to use.

Main

Mandarine's DI Container serves as the main source for your components to ask for dependencies. This means, all the resolved dependencies are found inside the DI container.
Usually, accessing a resolved component is achieved by using injection by construction or manual injection. But some use cases may require something different such as accessing the dependency programmatically.
Accessing a dependency programmatically allows you to connect a non-mandarine-powered application with a Mandarine-powered application. This means, you can mix features such as native javascript/typescript and dependency injection in your application. Even though the use cases for this may vary, it is always recommended to develop Mandarine-powered applications in order to get full access to all its features.

Usage

1
import { Component, ApplicationContext } from "https://deno.land/x/mandarinets/mod.ts";
2
3
@Component()
4
export class MyComponent {
5
6
public pi() {
7
return 3.14;
8
}
9
10
}
11
12
class TSNativeClass {
13
14
public getPiFromDIContainer() {
15
return ApplicationContext.getInstance()
16
.getDIFactory()
17
.getDependency(MyComponent)
18
.pi();
19
}
20
21
}
22
23
// Let Mandarine's core resolve dependencies and initialize the DI engine
24
new MandarineCore();
25
26
let pi = new TSNativeClass().getPiFromDIContainer();
27
28
console.log(pi);
29
30
/**
31
* RESULT:
32
* 3.14;
33
*/
34
Copied!
In the example above we are looking how a regular typescript class that has no relation with a mandarine-powered class whatsoever is getting the resolved component of the class MyComponent and we can see how it is able to use it & call its properties.
Note that in order to accomplish the shown example, it is necessary to use new MandarineCore() as it is responsible for resolving Mandarine-powered components as well as the needed resources for a Mandarine application or partial Mandarine application to work. For more information about this, click here.
Last modified 1yr ago
Copy link