Service scopes

DiVine uses a hierarchy of containers, called the container tree, that includes the root container and sub-containers. You may use sub-containers, when separate parts of your code needs separate dependencies.

By default, service scopes are CONTAINER, which means that a unique instance is associated for each container, that requests the dependency. If you want a service to be unique in the whole container tree, consider using @Service(scope=SINGLETON) to indicate, that no matter what container is the code requesting the dependency from, the same instance should be retrieved.

You can use the following methods to request various containers depending on the call context.

void testContainers() {
    // will return the root container of the container tree
    Container.ofGlobal();
    
    // will return a sub-container called `my-container`, that is a 
    // child of the root container
    Container.ofGlobal("my-container"); 
    
    // // will return a unique container for the call context, that is a child
    // of the root container, and is called `container-%container_id_increment%`
    Container.ofContext(); 
    
    // will return a unique sub-container of `Container.ofContext()`, 
    // which is called `other-container`, and is a child of the root container
    Container.ofContext("other-container"); 
}

If you want to learn more about container contexts, check out the Container contexts part in Advanced usage.

The following code is an example, in which container-scoped services come in handy.

@Service
class PlayerManager {
    public List<Player> getPlayers() { /* player list logic*/ }
}

@Service
class MinigameArena { 
    @Inject
    private PlayerManager playerManager;
    
    public void start() {
        for (Player player : playerManager.getPlayers()) {
            player.message("Arena is starting...");
        }
    }
}

void manageArenas() {
    // the following code will resolve the dependency tree for two separate 
    // minigame arenas, where each arena will request their own instance 
    // of dependencies
    MinigameArena foo = fooArenaContainer.get(MinigameArena.class);
    MinigameArena bar = barArenaContainer.get(MinigameArena.class);
    assert foo != bar;
}

Last updated