Cake パターンを使用して Scala に依存性注入を実装しようとしていますが、依存性衝突が発生しています。このような依存関係を持つ詳細な例が見つからなかったため、ここに私の問題があります:
次の特性があるとします (2 つの実装があります)。
trait HttpClient {
def get(url: String)
}
class DefaultHttpClient1 extends HttpClient {
def get(url: String) = ???
}
class DefaultHttpClient2 extends HttpClient {
def get(url: String) = ???
}
そして、次の 2 つのケーキ パターン モジュール (この例では、どちらも機能を our に依存する API ですHttpClient
):
trait FooApiModule {
def httpClient: HttpClient // dependency
lazy val fooApi = new FooApi() // providing the module's service
class FooApi {
def foo(url: String): String = {
val res = httpClient.get(url)
// ... something foo specific
???
}
}
}
と
trait BarApiModule {
def httpClient: HttpClient // dependency
lazy val barApi = new BarApi() // providing the module's service
class BarApi {
def bar(url: String): String = {
val res = httpClient.get(url)
// ... something bar specific
???
}
}
}
両方のモジュールを使用する最終的なアプリを作成するときは、両方httpClient
のモジュールに依存関係を提供する必要があります。しかし、モジュールごとに異なる実装を提供したい場合はどうでしょうか? それとも、別の方法で構成された依存関係の別のインスタンスを提供するだけExecutionContext
ですか?
object MyApp extends FooApiModule with BarApiModule {
// the same dependency supplied to both modules
val httpClient = new DefaultHttpClient1()
def run() = {
val r1 = fooApi.foo("http://...")
val r2 = barApi.bar("http://...")
// ...
}
}
モジュールごとに依存関係に異なる名前を付けて、モジュール名の前に付けることができますが、それは面倒で洗練されていません。また、モジュールを自分で完全に制御できない場合は機能しません。
何か案は?私はケーキのパターンを誤解していますか?