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

import { Component, ApplicationContext } from "https://deno.land/x/mandarinets/mod.ts";

@Component()
export class MyComponent {

    public pi() {
        return 3.14;
    }

}

class TSNativeClass {

    public getPiFromDIContainer() {
        return ApplicationContext.getInstance()
                                 .getDIFactory()
                                 .getDependency(MyComponent)
                                 .pi();
    }

}

// Let Mandarine's core resolve dependencies and initialize the DI engine
new MandarineCore();

let pi = new TSNativeClass().getPiFromDIContainer();

console.log(pi);

/**
 * RESULT:
 * 3.14;
 */

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 updated