Skip to content

Entity Loader Service

Introduction

The EntityLoaderService handles all loading (creating / instantiating) and unloading of Entities. The service either creates new Entities or returns existing ones from the Container.

Note

This page makes references to the Dependency Container and Entity Life Cycle pages in passing. It is recommended to get a high-level understanding of these systems before proceeding.

LoadEntity

Note

Before using the EntityLoaderService to load Entities, the Entities' IData must have been loaded by the IDataProvider and cached using the IDataService. This would usually happen during the LoadContentDataLoadPhase. Check out the startup process page to learn more about the load phases.

When LoadEntity is called, the service checks if the Entity exists in the Container:

  • If the Entity exists, the Entity is simply retrieved.

  • If the Entity doesn't exist, EntityLoaderService.CreateEntity is then called to create and bind the Entity in the Container. After that, the service resolves the Entity from the Container, which injects the Entity's dependencies. This process will usually recursively create the dependent Entities for this Entity. For example, creating the Content will, in turn, load the Stages.

When LoadEntity is performed, the service increments an internal reference count of the loaded Entity. Every subsequent call to load the same Entity would increment the reference count further. This is an important step to remember as it is used in UnloadEntity to determine if the Entity should be unbound from the Container.

Warning

LoadEntity should only be called from an object that owns the Entity that is being loaded. For example, a Content calls LoadEntity to load its Stages. Classes using LoadEntity should also call UnloadEntity on Cleanup() and set the Entity references to null to avoid memory leak. LoadEntity should never be called by UI classes for the same reason. Instead, those classes should use the Resolver to locate their dependent Entities.

CreateEntity

EntityLoaderService.CreateEntity first retrieves the Entity's IData that has previously been cached by the IDataService. It then creates the Entity object by calling the IEntityData.CreateEntity and binds its actual type, parent types, and interfaces to its Id in the Container. If the Entity's IData is an ISavedDataProvider, it also creates and binds the Entity saved data's actual type, parent types, and interfaces to its Id as well.

Tip

Check out the Understanding Entities for the complete flow of the IEntity creation.

UnloadEntity

In EntityLoaderService.UnloadEntity, the reference count is decremented for the Entity. If there are no more references left, the Entity and its saved data are then unbound from the Container.