Correct Way of Retrieving a Service

Hi there,

Just like to clarify if there’s a correct way in retrieving a service. In the documentation. We can retrieve a service in Kotlin using either of the following:

val applicationService = service<MyAppService>()

val projectService = project.service<MyProjectService>()

But when I look at the documentation for the service<T>() function, it recommends adding a getInstance(Project) method to access the service:

/**
 * Initializes the service instance if not yet initialized, and returns the service instance.
 *
 * This is primarily intended to be used by the service implementation. When introducing a new service,
 * please add a static `getInstance(Project)` method. For better tooling performance, it is always advised
 * to keep an explicit method return type.
 * ```kotlin
 * @Service
 * class MyProjectService(private val project: Project) {
 *
 *   companion object {
 *
 *     @JvmStatic
 *     fun getInstance(project: Project): MyProjectService = project.service()
 *   }
 * }
 * ```
 *
 * @throws IllegalStateException if a service cannot be found in [this] component manager
 * @see ComponentManager.getService
 */
inline fun <reified T : Any> ComponentManager.service(): T {
  val serviceClass = T::class.java
  return getService(serviceClass) ?: throw serviceNotFoundError(serviceClass)
}

Are any of the above approaches fine to use, or should we always add a getInstance() class?

From our experience, it is better to always have getIntances() for debugging convenience to easily find clients/usages of APIs, while it is not a strong recommendation nowadays.

@yuriy.artamonov thanks! So I guess either approach is ok, just a matter of having able to put a breakpoint in the instance creation when using getInstace() vs less line of code by using service<T>() calls?