How to create a new instance of an service class or SObject wrapper

Normally in APEX you would instantiate the following way:

EventService es = new EventService();

The issue with this method is that there is no way to override this globally or even keep stability during upgrades. This puts a hard requirement on the EventService class directly and only allows us to instantiate it.

To resolve this issue, we are introducing Dependency Injection (DI) in the new platform. The same code above will be written as:

EventService es = EventService.getInstance();

The above code will instantiate the EventService using the base abstract class. The getInstance method will check if there is a global override using Custom Metadata Types (CMT). If there is an override, it will return that object instead of the base EventService. The class override needs to extend the EventService class to make sure it is instantiated correctly. Not all methods in the service will be overridable, which allows core functionality to work without hinderance. This further allows us to also version the service class that is returned, so as customers upgrade the platform they can stay with an older version of that service class to reduce the impact.

All instantiations for both service classes and SObject wrapper classes need to use the getInstance method. This allows us to use the overrides within our platform and not just when customers interact with our platform.