본문 바로가기

안드로이드/DI

Service Locator

Service Locator 방식은 수동으로 의존성을 주입해주는 방식이다.

위와 같이 각 클래스를 ServiceLocator 클래스에 정의해둔 뒤, 싱글톤인 Application 클래스에 초기화 해주고 Application에서 가져다가 직접 주입해주는 방법으로 이루어진다.

 

class A
class B
class C

class ServiceLocator{
	private val a = A()
	private val b = B()
	private val c = C()

	fun getA() = a
	fun getB() = b
	fun getC() = c
}

class MyApplication: Application() {

    override fun onCreate() {
        super.onCreate()

        serviceLocator = ServiceLocator()
    }

    companion object {
		    // 싱글톤 생략
		    
        lateinit var serviceLocator: ServiceLocator
    }
}

class MainActivity: AppCompatActivity() {
	private val testClass = TestClass(MyApplication.serviceLocator.getA()) // 직접 주입
	...
}

 

단점

  1. 의존성 주입이 필요한 클래스가 많아지면 위와 같은 코드가 많아지고, 관리가 어려워진다.
    • 어디서 어떻게 주입되는지 알기 어려워지는 경우가 생김
  2. 테스트가 어렵다.
  3. Service Locator가 갖고 있는 다른 클래스들에 대한 의존이 함께 발생
  4. 런타임 과정에서 의존성 주입이 일어나기 때문에 런타임 과정에서 오류가 발생할 수 있다.

'안드로이드 > DI' 카테고리의 다른 글