Skip to Content
CrowCrow

Dependency Injection (crow-inject)

Compile-time K2 scoped lifetime graphs, injected @Ui screens, Async dependencies under Loading, keyed session scopes, and two-line test overrides.

crow-inject is Crow's compile-time, owner-scoped dependency injection library built directly into the K2 Crow compiler plugin (CR2001–CR2007, zero KSP/kapt).

Core Concepts

  • Scopes match lifetimes: @AppGraph graphs live for the OS process; screen graphs live for their BackStack entry under InjectedNavHost; @KeyedScope boundaries (ScopeHost(Session::class)) automatically unmount UI and dispose in strict reverse dependency order when @ScopeKey changes.
  • No scope leaks: Compile-time CR2004 checks prevent longer-lived scopes from depending on shorter-lived or missing keyed scopes.
  • Async<T> dependencies: Provide asynchronous services (async { ... }) as graph-owned resources that suspend cleanly under a Loading boundary or .await() off-UI.
  • Lazy & Provider: Defer instantiation or break intentional cycles with Lazy<T> or () -> T.

Providing & Injecting Screens

@ContributesBinding(App::class)
@Inject
class RealTvShowApi : TvShowApi { /* ... */ }

@Inject
@Scoped(Screen::class)
class ShowDetailsModel(
    val route: ShowDetailsRoute,
    val api: TvShowApi,
) : StateHolder() {
    var bookmarked by saved(false)
}

@Inject
@Ui
fun ShowDetailsScreen(@Once route: ShowDetailsRoute, @Once model: ShowDetailsModel) {
    // Parameters are resolved directly from the generated screen graph
}

@AppGraph
interface AppRoot {
    val api: TvShowApi
}

// Wire at the app root:
val graph = createGraph<AppRoot>()
InjectHost(graph) {
    InjectedNavHost(backStack)
}

Two-Line Test & Preview Overrides

Swap real network clients or stores for type-checked fakes in any headless test or preview without touching production wiring:

val testGraph = createGraph<AppRoot> {
    replace<TvShowApi>(FakeTvShowApi())
    replace<WatchlistRepo>(InMemoryWatchlistRepo())
}

For scoped subtree overrides in previews (unscoped or strictly deeper-scoped bindings), wrap the subtree in Overrides({ replace<String>("Preview") }) { ... }.

Disposal order and scope lifetimes are verified by multi-seed property tests across compiled random DAGs and randomized navigation + keyed-scope transitions, ensuring dependents always close before their dependencies and UI always unmounts before holders clear.

How is this guide?

On this page