Introduction

OstroJS has the ability to save classes in containers and reuse singleton or binding classes.

Building a strong, big application, as well as contributing to the OstroJS core, requires a thorough grasp of the OstroJS service container.

Binding

Simple Bindings

Because nearly all of your service container bindings will be registered within service providers, the majority of these examples will show how to use the container in that context.

The container is always accessible within a service provider via the this.$app property. The bind function may be used to register a binding by supplying the class or interface name to be registered along with a closure that returns an instance of the class:

this.$app.bind('foo', function (app) {
    return new Bar(app);
});

It's worth noting that we pass the container itself to the resolver as an argument.

As previously said, you'll most often connect with the container through service providers; but, if you want to interface with the container outside of a service provider, you may do so using the App facade:

app.bind('foo/bar', function ($app) {
    // ...
});

Binding A Singleton

The singleton method attaches a class or interface that should only be resolved once into the container. When a singleton binding is resolved, future calls to the container will return the same object instance:

this.$app.singleton('transistor', function (app) {
    return new Transistor(app.make('app/services/podcastParser'));
});

Binding Instances

The instance method can also be used to tie an existing object instance to the container. On future calls to the container, the supplied instance will always be returned:

const Transistor = require('app/services/transistor')
const PodcastParser =  require('app/services/podcastParser')

$service = new Transistor(new PodcastParser);

this.$app.instance('transistor', $service);

Resolving

The Make Method

To resolve a class instance from the container, use the make method. The name of the class or interface you want to resolve is sent to the make method:

const transistor = this.$app.make('~/app/services/transistor');

If any of your class's dependencies aren't resolved by the container, you may inject them using the makeWith function by supplying them as an associative argument. For example, we might explicitly supply the Transistor service's $id constructor argument:


const transistor = this.$app.makeWith('app/service/transistor', 1);

If you're working outside of a service provider and don't have access to the $app variable, you may use the App façade to get a class instance from the container:

const Transistor =  require('app/services/transistor');
const App = require('@ostro/support/facades/app');

const transistor = App.make(Transistor);