Skip to content
Brian Kotek edited this page Aug 20, 2013 · 4 revisions

Back to Advanced IoC Configuration

A dependency provider can also specify a function to use to create the object that will be injected:

Deft.Injector.configure({

  contactStore: {
    fn: function() {
      if (useMocks) {
        return Ext.create("MyApp.mock.store.ContactStore");
      } else {
        return Ext.create("MyApp.store.ContactStore");
      }
    },
    eager: true
  },

  contactManager: {
    // The factory function will be passed a single argument:
    // The object instance that the new object will be injected into
    fn: function(instance) {
      if (instance.session.getIsAdmin()) {
        return Ext.create("MyApp.manager.admin.ContactManager");
      } else {
        return Ext.create("MyApp.manager.user.ContactManager");
      }
    },
    singleton: false
  }

});

When the Injector is called to resolve dependencies for these identifiers, the factory function is called and the dependency is resolved with the return value.

As shown above, a lazily instantiated factory function can optionally accept a parameter, corresponding to the instance for which the Injector is currently injecting dependencies.

Factory function dependency providers can be configured as singletons or prototypes and can be eagerly or lazily instantiated.

NOTE: Only singleton factory functions can be eagerly instantiated. This means that specifying singleton: false and eager: true for a dependency provider won't work. The reason may be obvious: Deft JS can't do anything with a prototype object that is eagerly created, since by definition each injection of a prototype dependency must be a new instance!

Next: Mapping Values to Dependency Identifiers