Skip to content

Private

Mauro Gadaleta edited this page Mar 16, 2017 · 1 revision

Marking Services as Public / Private

When defining services, you'll usually want to be able to access these definitions within your application code. These services are called public. This means that you can fetch it from the container using the get() method:

let publicManager = container.get('public_manager')

In some cases, a service only exists to be injected into another service and is not intended to be fetched directly from the container as shown above.

In these cases, to get a minor performance boost and ensure the service will not be retrieved directly from the container, you can set the service to be not public (i.e. private):

import {ContainerBuilder} from 'node-dependency-injection'
import SomeManager from './SomeManager'

let container = new ContainerBuilder()
let definition = container.register('some_manager') // Returns a new Definition instance
definition.public = false
With Configuration files
YAML
services:
    some_manager:
        class: ./SomeManager
        public: false
JSON
{
  "services": {
    "some_manager": {
      "class": "./SomeManager",
      "public": false
    }
  }
}

Finally if we do

let someManager = container.get('some_manager')

Now that the service is private, you should not fetch the service directly from the container. This will throw an exception The service {service name} is private

Services are by default public, but it's considered a good practice to mark as more services private as possible.