Cake Figure: how to get all UserService objects provided by components

This question can help you understand my needs. Cake sample: one component for each implementation or one component for each attribute?

I have a Scala application using several UserService implementations that will be provided by component (s?).

I wonder if there is a way in another component to β€œscan” the application so that I can get a set of all components that provide an object that implements the UserService property? So that I can iterate through all the UserService interfaces provided by my cake making application?

I think I may have a component that builds a UserService list depending on its dependency, but is it possible for this component to create a list without any hard-coded dependency?

+3
source share
1 answer

You can simply have a list of instances UserServiceright in UserServiceComponentand have a base UserServicecase on that list.

trait UserServiceComponent {
  private val _userServices = collection.mutable.Buffer[UserService]()
  def userServices: Seq[UserService] = _userServices.synchronized {
    _userServices.toList // defensive copy
  }
  private def registerUserService( service: UserService ) = _userServices.synchronized {
    _userServices += service
  }

  trait UserService {
    registerUserService( this )

    def getPublicProfile(id: String): Either[Error, User]
  }

  val mainUserService: UserService
}

trait DefaultUserServiceComponent extends UserServiceComponent { self: UserRepositoryComponent =>
  protected class DefaultUserService extends UserService {
    // NOTE: no need to register the service, this is handled by the base class
    def getPublicProfile(id: String): Either[Error, User] = userRepository.getPublicProfile(id)
  }
  val mainUserService: UserService = new DefaultUserService
}
+6
source

All Articles