Skip to content

DSL リファレンス ​

このページでは、すべてのKoin DSLキーワードを表形式でリストアップし、インポートするパッケージと解説ページへのリンクを掲載しています。Compiler Plugin DSL、Constructor DSL(コンストラクタ参照)、Classic DSL(ラムダ)の3つのDSL形式を網羅しています。アノテーションについては、Annotations Referenceを参照してください。

DSL スタイル ​

スタイル例インポート
Compiler Plugin DSLsingle<UserRepository>()org.koin.plugin.module.dsl.*
Constructor DSLsingleOf(::UserRepository)org.koin.core.module.dsl.*
Classic DSLsingle { UserRepository(get()) }org.koin.dsl.*

Compiler Plugin DSLにはKoin Compiler Pluginが必要です。プラグインはコンストラクタを読み取り、get()の呼び出しを生成して、ビルド時にグラフをチェックします。プラグインがない場合、single<T>()のような呼び出しは実行時に次のような例外をスローします:Error while using 'single<T>()'. The Koin Compiler plugin is missing. Please fix your setup to use 'io.insert-koin.compiler.plugin' Koin Gradle Plugin.

コンストラクタ参照の形式(singleOf(::T))も、Compiler Pluginが適用されている場合はチェックされます。手書きのラムダはチェックされません。プラグインはラムダ本体の処理ではなく、それが提供する型のみを追跡します。スタイルの選択については、Choosing your styleを参照してください。

Application DSL ​

Koinコンテナを作成して起動する関数です。Starting Koinを参照してください。

関数パッケージ説明
startKoin { }org.koin.core.contextKoinApplicationを作成し、グローバルコンテキストに登録します。すでに起動している場合はKoinApplicationAlreadyStartedExceptionをスローします
startKoin<T>()org.koin.plugin.module.dslCompiler Plugin: @KoinApplicationクラスTのモジュールを使用してKoinを起動します
koinApplication { }org.koin.dslグローバルに登録されないスタンドアロンのKoinApplicationを作成します。Context Isolationを参照してください
koinApplication<T>()org.koin.plugin.module.dslCompiler Plugin: Tのモジュールを持つスタンドアロンアプリケーションを作成します
koinConfiguration { }org.koin.dslKoinを起動せずに再利用可能なKoinConfigurationを宣言します
koinConfiguration<T>()org.koin.plugin.module.dslCompiler Plugin: Tのモジュールを持つ設定を作成します
stopKoin()org.koin.core.contextグローバルコンテナとそのすべてのインスタンスをクローズします
loadKoinModules(module)org.koin.core.context起動しているグローバルコンテナにモジュールをロードします
unloadKoinModules(module)org.koin.core.contextモジュールをアンロードし、そのインスタンスを破棄します

startKoin { } および koinApplication { } の内部 ​

関数説明
modules(...)モジュールをロードします: 単一のModule、可変長引数、またはList<Module>
modules(UserModule::class, ...)Compiler Plugin: @Moduleクラスから生成されたモジュールをロードします
module<UserModule>()Compiler Plugin: 単一の@Moduleクラスから生成されたモジュールをロードします
withConfiguration<T>()Compiler Plugin: 既存のアプリケーションに@KoinApplicationクラスTのモジュールを追加します
includes(configuration)1つ以上のKoinConfigurationまたはKoinAppDeclarationブロックを適用します
printLogger(level)標準出力にログを出力します。デフォルトレベルはLevel.INFOです
logger(logger)独自のLogger実装を使用します。デフォルトはEmptyLogger(出力なし)です
properties(map)Map<String, Any>からプロパティをロードします
fileProperties(fileName)JVMのみ。ファイルからプロパティをロードします(デフォルトは/koin.properties)
environmentProperties()JVMのみ。システムプロパティと環境変数をロードします
allowOverride(Boolean)定義のオーバーライドを許可または禁止します。デフォルトはtrueです。Definitionsを参照してください
createEagerInstances()createdAtStart定義を作成します。startKoinとkoinApplicationはすでにこれを呼び出しています
options(...)viewModelScopeFactory()などのKoinオプションを設定します。ViewModelを参照してください
lazyModules(...)バックグラウンドで遅延モジュールをロードします(koin-core-coroutines)。Lazy Modulesを参照してください

modules(A::class)、module<T>()、withConfiguration<T>()は、startKoin<T> { }の内部ではなく、通常のstartKoin { }またはkoinApplication { }内に配置します。

プラットフォーム拡張機能により、このブロックにさらに多くの関数が追加されます:

関数アーティファクト参照
androidContext(context), androidLogger(level), androidFileProperties()koin-androidAndroid Start
fragmentFactory()koin-androidFragment Factory
workManagerFactory()koin-androidx-workmanagerWorkManager
slf4jLogger(level)koin-logger-slf4jKtor

Module DSL ​

ModulesおよびLazy Modulesを参照してください。

関数パッケージ説明
module { }org.koin.dslモジュールを宣言します
module(createdAtStart = true) { }org.koin.dslモジュールのすべてのsingleが起動時に作成されます
lazyModule { }org.koin.dsl後からバックグラウンドでロードされるモジュールを宣言します(koin-core-coroutines)
includes(otherModule, ...)org.koin.dsl他のモジュールを可変長引数またはCollection<Module>としてインクルードします
moduleA + moduleBorg.koin.dslList<Module>を構築します

定義(Definitions) ​

各キーワードが何を作成するかについては、Definitionsで解説されています。

定義Compiler Plugin DSLConstructor DSLClassic DSL
Singlesingle<T>()singleOf(::T)single { T(get()) }
Factoryfactory<T>()factoryOf(::T)factory { T(get()) }
Scoped(スコープブロック内)scoped<T>()scopedOf(::T)scoped { T(get()) }
ViewModelviewModel<T>()viewModelOf(::T)viewModel { T(get()) }
Worker(Android)worker<T>()workerOf(::T)worker { T(get(), get()) }
Fragment(Android)利用不可fragmentOf(::T)fragment { T(get()) }
関数またはビルダーsingle { create(::buildT) }singleOf(::buildT)single { buildT(get()) }

パッケージ:

キーワードCompiler Plugin DSLConstructor / Classic DSL
single, factory, scoped, createorg.koin.plugin.module.dslorg.koin.dsl(ラムダ)、org.koin.core.module.dsl(singleOf、factoryOf、scopedOf、new)
viewModel, viewModelOf(アーティファクト koin-core-viewmodel)org.koin.plugin.module.dslorg.koin.core.module.dsl
worker, workerOf(アーティファクト koin-androidx-workmanager)org.koin.plugin.module.dslorg.koin.androidx.workmanager.dsl
fragment, fragmentOf(アーティファクト koin-android)org.koin.androidx.fragment.dsl

org.koin.androidx.viewmodel.dslおよびorg.koin.compose.viewmodel.dslのviewModelとviewModelOfは非推奨(deprecated)です。org.koin.core.module.dslからインポートしてください。

create(::buildT)は、ラムダ内の唯一の命令である必要があります。そうでない場合、Compiler Pluginはcreate(::buildT) must be the only instruction in the lambda.と報告します。Definitionsを参照してください。

ラムダパラメータ ​

ラムダ定義は以下のシグネチャを持ちます:

キーワードパラメータ
single(qualifier, createdAtStart) { }qualifier: Qualifier? = null, createdAtStart: Boolean = false
factory(qualifier) { }qualifier: Qualifier? = null
scoped(qualifier) { }qualifier: Qualifier? = null
viewModel(qualifier) { }qualifier: Qualifier? = null
worker(qualifier) { }qualifier: Qualifier = named<T>()

定義ラムダの内部 ​

ラムダはScopeレシーバとParametersHolder引数(params)を持って実行されます:

関数戻り値参照
get<T>(), get<T>(qualifier)インスタンス。見つからない場合はNoDefinitionFoundExceptionをスローInjection
getOrNull<T>()インスタンスまたはnullInjection
inject<T>()Lazy<T>Injection
getAll<T>()TにバインドされたすべてのインスタンスAdvanced Patterns
getProperty(key), getProperty(key, default), getPropertyOrNull(key)KoinプロパティStarting Koin
params.get<T>(), (id) -> ... 分解宣言注入されたパラメータInjected Parameters
new(::T)すべてのコンストラクタパラメータがget()によって解決された新しいT
create(::T)Compiler Plugin: 上記と同じで、ビルド時チェック付きDefinitions
getSource<T>()スコープのソースオブジェクトScopes
androidContext(), androidApplication()AndroidのContextまたはApplicationAndroid Start

定義のオプション ​

オプションは、中置演算子を使用するかwithOptions { }ブロック内で定義の後に適用します。すべての定義キーワードで機能します。

オプション形式説明参照
bindsingle<T>() bind I::classセカンダリ型を追加しますDefinitions
bindssingle<T>() binds arrayOf(I::class, J::class)複数のセカンダリ型を追加しますDefinitions
onClosesingle<T>() onClose { it?.close() }インスタンス解放時のコールバックDefinitions
withOptions { }single<T>() withOptions { ... }以下のオプションブロックを開きます
.override()single<T> { ... }.override()allowOverride(false)が設定されている場合に、許可されたオーバーライドとしてマークしますDefinitions

withOptions { }内、またはsingleOf(::T) { }、factoryOf、scopedOf、viewModelOfの末尾ブロック内:

オプション説明
named("name")文字列修飾子。Qualifiersを参照
named<Type>()型修飾子
bind<I>()セカンダリ型を追加します
binds(listOf(I::class, J::class))複数のセカンダリ型を追加します
createdAtStart()Koin起動時にsingleを作成します
onClose { }解放時のコールバック
kotlin
val appModule = module {
    single<UserRepositoryImpl>() withOptions {
        named("local")
        bind<UserRepository>()
        createdAtStart()
    }

    // Constructor DSL
    singleOf(::UserRepositoryImpl) {
        named("local")
        bind<UserRepository>()
    }
}

Scope DSL ​

スコープブロックは、スコープと同じ生存期間を持つ定義をグループ化します。Scopesを参照してください。

関数パッケージ説明
scope<T> { }Moduleメンバー型Tによって識別されるスコープ(通常はスコープソースの型)
scope(named("session")) { }Moduleメンバー修飾子によって識別されるスコープ

スコープブロック内:

定義Compiler Plugin DSLConstructor DSLClassic DSL
Scopedscoped<T>()scopedOf(::T)scoped { T(get()) }
Factoryfactory<T>()factoryOf(::T)factory { T(get()) }
ViewModelviewModel<T>()viewModelOf(::T)viewModel { T(get()) }
Worker(Android)worker<T>()workerOf(::T)worker { T(get(), get()) }
kotlin
val sessionModule = module {
    scope<UserSession> {
        scoped<SessionCache>()
        factory<SessionPresenter>()
    }
}

スコープアーキタイプ ​

アーキタイプは、単一のクラスではなく、特定タイプのスコープソース向けのスコープブロックです。その種類のすべてのソースがその定義を受け取ります。

関数アーティファクト対象スコープ参照
viewModelScope { }koin-core-viewmodel各ViewModelViewModel
activityScope { }koin-android各ActivityAndroid Scopes
activityRetainedScope { }koin-android各Activity(構成変更をまたいで保持)Android Scopes
fragmentScope { }koin-android各FragmentAndroid Scopes
navigationScope { }koin-compose-viewmodel-navigation各ナビゲーションデスティネーション(NavBackStackEntry)Compose Scopes
requestScope { }koin-ktor各Ktor呼び出しKtor Scopes
  • Definitions: 各定義タイプの役割と使用すべきタイミング。
  • Modules: モジュールの整理と構成。
  • Scopes: スコープのライフサイクル、リンク、およびクローズ。
  • Annotations Reference: このページに対応するアノテーションのリファレンス。
  • Compiler Plugin Setup: Compiler Plugin DSLに必要なプラグインのセットアップ。