Skip to content

Dependency Injection

Web App Solution, Inc edited this page Apr 5, 2017 · 6 revisions

Back to Wiki Home

FlowMVC leverages DeftJS for dependency injection. Flex developers will find this a familiar concept from the use of frameworks like Parsley and Swiz. Dependency injection allows for configuration of dependencies either at run time or compile time. This decoupling allows developers to easily switch implementations for things like mocking of either services (dev or prod) or models at will.

In order for DeftJS to be loaded correctly, there are a few requirements. In a file that loads after the Sencha libraries load but prior to the loading of DeftJS we ensure certain Sencha classes are available:

/**
 * DeftJS relies on several core Sencha classes to function. For some strange reason, these core classes are
 * not part of the ext.js file, so you'll need to ensure that these classes are loaded and available before the
 * DeftJS library is loaded.
 */
Ext.syncRequire([
    "Ext.Component",
    "Ext.ComponentManager",
    "Ext.ComponentQuery"
]);

Developers familiar with dependency injection frameworks are familiar with the myriad ways to configure the IoC container wiring. DeftJS approach is a bit more straight-forward. Although they have created their own Application class (as well as other framework classes similar to those created by Sencha) we're going to stick as close to the Sencha paradigm as possible.

Wiring of objects to be injected is as simple as setting some name-value pairs within the Deft.Injector.configure function. We've chosen to this in the Ext.onReady function to ensure all dependencies are available for use prior to be needed. This is a familiar requirement in using dependency injections frameworks to ensure the framework is loaded early on in the application lifecycle.

Here we show how to wire a FlowMVC EventDispatcher for injection as a property called eventBus:

/**
 * Wiring the event bus and logger 
*/
Ext.onReady(function () {

    // pull all of this in so they can be injected
    Ext.syncRequire([
        "FlowMVC.mvc.event.EventDispatcher"
    ]);

    // Configure the DeftJS IoC container
    Deft.Injector.configure({

        ////////////////////////////////////////////
        // EVENT DISPATCHER
        ////////////////////////////////////////////
        eventBus:               "FlowMVC.mvc.event.EventDispatcher",

    });
});

Here we see this object being injected into the FlowMVC AbstractController class:

Ext.define("FlowMVC.mvc.controller.AbstractController", {
    extend: "Ext.app.Controller",

    inject: [
        "eventBus"
    ],

    ...
)};

We are ensured now that any reference to eventBus will be valid and useable at run time.