Dependency Graphs¶
The primary entry points in Metro are dependency graphs. These are interfaces annotated with @DependencyGraph and created with @DependencyGraph.Factory interfaces. Graphs expose types from the object graph via accessor properties or functions.
Tip
These are synonymous with components and @Component/@Component.Factory in Dagger and kotlin-inject.
Tip
“Accessors” in Metro are synonymous with Dagger’s provision methods.
Accessors and member injections act as roots, from which the dependency graph is resolved. Dependencies can be provided via conventional @Provides functions in graphs or their supertypes, constructor-injected classes, or accessed from graph dependencies.
@DependencyGraph
interface AppGraph {
val message: String
@Provides
fun provideMessage(): String = "Hello, world!"
}
Note the @Provides function must define an explicit return type.
Simple graphs like this can be created via the createGraph() intrinsic.
val graph = createGraph<AppGraph>()
Graphs are relatively cheap and should be used freely.
Inputs¶
Runtime inputs can be provided via a @DependencyGraph.Factory interface that returns the target graph. These parameters must be annotated with either @Provides or @Includes.
Provides¶
The simplest input is an instance parameter annotated with @Provides. This provides this instance as an available binding on the graph.
@DependencyGraph
interface AppGraph {
val message: String
@DependencyGraph.Factory
fun interface Factory {
fun create(@Provides message: String): AppGraph
}
}
Provided parameters may be any type.
Tip
This is analogous to Dagger’s @BindsInstance.
Includes¶
@Includes-annotated parameters are treated as containers of available bindings. Metro will treat accessors of these types as usable dependencies.
They are commonly other graph types whose’ dependencies you want to consume via explicit API.
@DependencyGraph
interface AppGraph {
val message: String
@DependencyGraph.Factory
fun interface Factory {
fun create(@Includes messageGraph: MessageGraph): AppGraph
}
@DependencyGraph interface MessageGraph {
val message: String
@Provides fun provideMessage(): String = "Hello, world!"
}
}
@Includes instance dependencies do not need to be other graphs though! They can be any regular class type. They cannot be enums or annotation classes.
@DependencyGraph
interface AppGraph {
val message: String
@DependencyGraph.Factory
fun interface Factory {
fun create(@Includes messageProvider: MessageProvider): AppGraph
}
interface MessageProvider {
val message: String
}
}
Warning
Includes parameters cannot be injected from the graph.
Binding Containers are a special type of @Includes type, see more in its section below.
Creating factories¶
Graph factories can be created with the createGraphFactory() intrinsic.
val messageGraph =
createGraphFactory<AppGraph.Factory>()
.create("Hello, world!")
Scoping¶
See Scopes for more details on scopes!
Graphs may declare a scope (and optionally additionalScopes if there are more). Each of these declared scopes act as an implicit @SingleIn representation of that scope for aggregation.
For example:
@DependencyGraph(AppScope::class)
interface AppGraph
Is functionally equivalent to writing the below.
@SingleIn(AppScope::class)
@DependencyGraph(AppScope::class)
interface AppGraph
Graph lifecycle¶
Graphs can run startup and cleanup code in annotated callback functions. Metro calls each callback, injects its parameters, and validates them with the rest of the graph.
A graph opts in by implementing CloseableGraph or SuspendCloseableGraph and annotating functions with @OnGraphInit or @OnGraphClose.
@SingleIn(AppScope::class)
@Inject
class Analytics {
fun start() { /* ... */ }
fun flush() { /* ... */ }
}
@DependencyGraph(AppScope::class)
interface AppGraph : CloseableGraph {
@OnGraphInit
fun initialize(analytics: Analytics) {
analytics.start()
}
@OnGraphClose
fun shutdown(analytics: Analytics) {
analytics.flush()
}
}
CloseableGraph extends AutoCloseable, so use {} works with it too. SuspendCloseableGraph has a suspend close() for cleanup that suspends. Metro generates the implementation of close(), so implementing it yourself is reported as a compiler error.
Callbacks¶
Callbacks are ordinary functions with a body that return Unit. Each function can have only one lifecycle annotation. A graph can have any number of callbacks, with or without parameters. They run in no particular order.
Only Metro may invoke these functions. Calling one directly or taking a reference to it is an error. An override can still call the callback it overrides through super.
The names are hopefully self-explanatory! Init callbacks run after the graph’s own initialization. If one fails or creation is cancelled, creation stops there.
Note
Graph factories and createGraph() return the graph only after every init callback succeeds.
Warning
Metro doesn’t run close callbacks to undo partial startup, so release anything acquired before the failure yourself.
Contributed callbacks¶
A contributed interface can bring its own callbacks.
@ContributesTo(AppScope::class)
interface AnalyticsLifecycle {
@OnGraphInit
fun initializeAnalytics(analytics: Analytics) {
analytics.start()
}
@OnGraphClose
fun closeAnalytics(analytics: Analytics) {
analytics.flush()
}
}
- The graph that the interface is contributed to must implement
CloseableGraphorSuspendCloseableGraph(the interface itself doesn’t have to). - Metro calls an inherited callback exactly once, even through diamond inheritance.
- An override replaces the inherited callback.
- It can call the inherited callback with
super. - It must re-declare the callback’s annotation and the qualifiers on its own parameters.
Callback parameters¶
Callback parameters use normal dependency resolution and get the same compile-time validation as graph accessors. This allows you to easily consume and use dependencies in your callback functions.
Warning
Close callbacks have two traps! Metro warns about both. Suppress either warning when you intend that behavior.
- A binding that nothing else requests can be created during close just to be cleaned up.
- An unscoped binding gives the callback a new instance, so cleaning it up leaves the one the rest of the graph used untouched.
UnscopedLifecycleParameter reports any callback parameter that requests an unscoped binding directly (not including graph inputs or values from included graphs). Request () -> T or Lazy<T> to circumvent this, but only if you need to!
CloseOnlyBinding reports a binding that only close callbacks request.
Closing a graph¶
The first call to close() marks the graph closed and runs any @OnGraphClose callbacks. Later calls return immediately, even while cleanup is running, so close callbacks run at most once. A close callback or extension that fails doesn’t stop the rest of cleanup. close() throws the first failure after cleanup finishes, with later failures attached as suppressed exceptions.
Post-close graph usage
A closed graph still serves dependency requests. A request after close can create a binding for the first time, so stop using a graph before you close it.
Closing also doesn’t clear cached instances. A closed graph and its providers keep them in memory until you allow it to be GC’d naturally.
Creating a graph extension through a closed graph fails, even with a factory obtained earlier.
Graph extensions¶
Closing a graph closes its closeable extensions first, then runs its own close callbacks. Each extension closes its own extensions the same way. Closing an extension yourself removes it from its parent’s internal references.
val factory = appGraph.userGraphFactory
val first = factory.create(firstUser)
val second = factory.create(secondUser)
first.close()
appGraph.close() // Closes second, then runs appGraph's close callbacks. `first` is already closed
Warning
A CloseableGraph keeps a reference to each closeable extension it creates until the extension or the parent graph closes. Close extensions when you’re done with them so they can be garbage collected.
An extension joins its parent’s cleanup once its init callbacks succeed. If the parent closes while those callbacks run, creating the extension fails and Metro closes the extension first. The exception is an extension with a suspend close() that a non-suspend function creates, which stays open. A graph that receives another graph as an @Includes input doesn’t close it as there’s no parent/child relationship there. Sibling extensions close in no particular order when they are closed by their parents.
A CloseableGraph can’t own a SuspendCloseableGraph extension, but a SuspendCloseableGraph can own both kinds.
A graph that isn’t closeable can create closeable extensions too. It doesn’t track them, so close each one yourself. No graph above it can be closeable, because closing that graph couldn’t reach the extension.
Suspend callbacks¶
Callbacks can be suspend functions when suspend provider support is enabled.
A graph with a suspend init callback needs a graph factory whose creation function suspends. A non-suspend callback can’t request a binding that suspends. Request suspend () -> T or SuspendLazy<T> to defer it.
@DependencyGraph(AppScope::class)
interface AppGraph : CloseableGraph {
@OnGraphInit
suspend fun initialize(database: Database) {
database.migrate()
}
@DependencyGraph.Factory
fun interface Factory {
suspend fun create(@Provides config: AppConfig): AppGraph
// ^^^ create() is suspending
}
}
val factory = createGraphFactory<AppGraph.Factory>()
val graph = factory.create(config) // Returns after initialize() finishes
Obtaining the factory instance alone doesn’t suspend, only invoking its create function does. Graph extensions and dynamic graph factories follow the same rule through their @GraphExtension.Factory.
Suspend @OnGraphClose callbacks require SuspendCloseableGraph. Cancelling the caller of close() doesn’t interrupt cleanup. A failure still reaches the caller after cleanup finishes.
Tip
A graph with only suspending @OnGraphClose callbacks can be created without suspending.
Coroutines and resources¶
Scoped suspend bindings initialize in the caller’s coroutine context, so the graph doesn’t own that work. Closing a graph also doesn’t cancel or dispose of the instances it created, such as a CoroutineScope binding. You’re responsible for closing resources you own in an @OnGraphClose callback.
Tracing¶
With runtime tracing enabled, Metro records how long the init callbacks and close take, with a span for each callback. The graph doesn’t own its tracer, so closing the graph leaves the tracer open.
Graph Extensions¶
Dependency graphs can be extended via graph extensions. As the name implies, graph extensions extend a parent graph they are declared for and contain a superset of bindings that includes both the parent graph(s) as well as their own. These are similar in functionality to Dagger’s Subcomponents.
Graph extensions must be either an interface or an abstract class and are annotated with @GraphExtension. They are created via @GraphExtension.Factory types.
Metro’s compiler plugin will build, validate, and implement this graph at compile-time when the parent graph is generated. This means that graph extensions are not available until the parent graph is generated.
Graph extensions can be chained and implicitly inherit their parents’ scopes.
Creating Graph Extensions¶
You cannot create a graph extension independent of its parent graph, you may only access it via accessor on the parent graph. You can declare this in multiple ways:
- Declare an accessor on the parent graph directly.
@GraphExtension
interface LoggedInGraph
@DependencyGraph
interface AppGraph {
val loggedInGraph: LoggedInGraph
}
- (If the extension has a creator) declare the creator on the parent graph directly.
@GraphExtension
interface LoggedInGraph {
@GraphExtension.Factory
interface Factory {
fun createLoggedInGraph(): LoggedInGraph
}
}
@DependencyGraph
interface AppGraph {
val loggedInGraphFactory: LoggedInGraph.Factory
}
- (If the extension has a creator) make the parent graph implement the creator.
@GraphExtension
interface LoggedInGraph {
@GraphExtension.Factory
interface Factory {
fun createLoggedInGraph(): LoggedInGraph
}
}
@DependencyGraph
interface AppGraph : LoggedInGraph.Factory
- Contribute the factory to the parent graph via @ContributesTo. More on this below.
@GraphExtension(LoggedInScope::class)
interface LoggedInGraph {
@ContributesTo(AppScope::class)
@GraphExtension.Factory
interface Factory {
fun createLoggedInGraph(): LoggedInGraph
}
}
@DependencyGraph(AppScope::class)
interface AppGraph
Scoping¶
See Scopes for more details on scopes!
Like DependencyGraph, graph extensions may declare a scope (and optionally additionalScopes if there are more). Each of these declared scopes act as an implicit @SingleIn representation of that scope. For example:
@GraphExtension(AppScope::class)
interface AppGraph
Is functionally equivalent to writing the below.
@SingleIn(AppScope::class)
@GraphExtension(AppScope::class)
interface AppGraph
Providers¶
Like DependencyGraph, graph extensions may declare providers via @Provides and @Binds to provide dependencies into the graph.
Creators can provide instance dependencies and other graphs as dependencies.
@GraphExtension
interface AppGraph {
val httpClient: HttpClient
@Provides fun provideHttpClient(): HttpClient = HttpClient()
}
Graph-private Bindings¶
By default, all bindings in a graph are implicitly available to its graph extensions. @GraphPrivate allows marking @Provides, @Binds, or @Multibinds declarations as private to the graph they are provided in. This means:
- Private
@Providesand@Bindsbindings may not be exposed directly via an accessor. - The binding will not be visible to extensions of this graph.
Private bindings may be depended on by other bindings within the same graph as an implementation detail. @GraphPrivate @Multibinds declarations may also be requested from the graph that declares them; the privacy boundary only prevents them from being inherited by extensions.
Private Implementation Bindings¶
Use @GraphPrivate when a binding should be available as an implementation detail of its graph, but should not become part of that graph’s public accessor surface or extension surface.
@Inject
class ApiService(val httpClient: HttpClient)
@DependencyGraph(AppScope::class)
interface AppGraph {
val apiService: ApiService
@GraphPrivate
@Provides
fun provideHttpClient(): HttpClient = HttpClient()
// Error: cannot expose a @GraphPrivate binding as an accessor
val httpClient: HttpClient
fun loggedInGraph(): LoggedInGraph
}
@GraphExtension
interface LoggedInGraph {
// Error: HttpClient is @GraphPrivate in the parent and not visible here
val httpClient: HttpClient
}
Same-typed Scoped Bindings¶
@GraphPrivate is also useful when parent and child graphs both provide the same scoped type. The private binding remains available inside the graph that provides it, so consumers can request the plain type without qualifiers that only exist to distinguish graph ownership.
Compare a qualifier-based version with the same graph-local binding expressed with @GraphPrivate:
@Inject
class AppWorker(@Named("app") val scope: CoroutineScope)
@Inject
class LoggedInWorker(@Named("logged-in") val scope: CoroutineScope)
@DependencyGraph(AppScope::class)
interface AppGraph {
val appWorker: AppWorker
@Named("app")
@Provides
@SingleIn(AppScope::class)
fun provideCoroutineScope(): CoroutineScope = CoroutineScope("app")
val loggedInGraph: LoggedInGraph
}
@GraphExtension(LoggedInScope::class)
interface LoggedInGraph {
val loggedInWorker: LoggedInWorker
@Named("logged-in")
@Provides
@SingleIn(LoggedInScope::class)
fun provideCoroutineScope(): CoroutineScope = CoroutineScope("logged-in")
}
@Inject
class AppWorker(val scope: CoroutineScope)
@Inject
class LoggedInWorker(val scope: CoroutineScope)
@DependencyGraph(AppScope::class)
interface AppGraph {
val appWorker: AppWorker
@GraphPrivate
@Provides
@SingleIn(AppScope::class)
fun provideCoroutineScope(): CoroutineScope = CoroutineScope("app")
fun loggedInGraph(): LoggedInGraph
}
@GraphExtension(LoggedInScope::class)
interface LoggedInGraph {
val loggedInWorker: LoggedInWorker
@GraphPrivate
@Provides
@SingleIn(LoggedInScope::class)
fun provideCoroutineScope(): CoroutineScope = CoroutineScope("logged-in")
}
Graph-private Multibindings¶
Graph-local multibindings use the same pattern, but the private binding is the collection declaration plus its local contributions. This is useful for graph-local registries such as menu actions, navigation entries, or feature handlers. You can leave individual contributions public when they should continue to be visible to extensions.
data class MenuAction(val label: String)
@Inject
class AppMenu(val actions: Set<MenuAction>)
@Inject
class AccountMenu(val actions: Set<MenuAction>)
@DependencyGraph(AppScope::class)
interface AppGraph {
val appMenu: AppMenu
@GraphPrivate
@Multibinds(allowEmpty = true)
val menuActions: Set<MenuAction>
@GraphPrivate
@Provides
@IntoSet
fun provideHelpAction(): MenuAction = MenuAction("Help")
fun loggedInGraph(): LoggedInGraph
}
@GraphExtension(LoggedInScope::class)
interface LoggedInGraph {
val accountMenu: AccountMenu
@GraphPrivate
@Multibinds(allowEmpty = true)
val menuActions: Set<MenuAction>
@GraphPrivate
@Provides
@IntoSet
fun provideSignOutAction(): MenuAction = MenuAction("Sign out")
}
fun example(appGraph: AppGraph) {
// appActions contains only "Help"
val appActions = appGraph.appMenu.actions
// loggedInActions contains only "Sign out"
val loggedInActions = appGraph.loggedInGraph().accountMenu.actions
}
Binds Implementation Notes
A non-private @Binds declaration may depend on a @GraphPrivate binding. In this case, the result type is visible to child graphs even though the source type is not. The child accesses the aliased type as a parent-resolved dependency rather than re-resolving the alias.
@DependencyGraph(AppScope::class)
interface AppGraph {
@GraphPrivate @SingleIn(AppScope::class) @Provides fun provideString(): String = "hello"
@Binds fun bindCharSequence(value: String): CharSequence
fun createChild(): ChildGraph
}
@GraphExtension
interface ChildGraph {
val text: CharSequence // OK — CharSequence is visible via the public @Binds alias
val string: String // Error — String is @GraphPrivate in the parent
}
Creators¶
See DependencyGraph’s section on creators.
Aggregation¶
See DependencyGraph’s section on aggregation.
Contributed Graph Extensions¶
Graph extensions may be contributed to a parent graph and its contribution merging will be deferred until the parent graph is generated.
The Problem¶
Imagine this module dependency tree:
:app
/ \
v v
:login :user-data
:app defines the main dependency graph with @DependencyGraph. The :login module defines a graph extension for authenticated user flows, and :user-data provides some core functionality like UserRepository.
If :login defines its own graph directly with @DependencyGraph, it won’t see contributions from :user-data unless :login depends on it directly.
The Solution¶
Instead, :login can use @GraphExtension(LoggedInScope::class) + @ContributesTo on its associated factory to say: “I want to contribute a new graph extension to a future AppScope parent graph.”
The graph extension will then be generated in :app, which already depends on both :login and :user-data. Now UserRepository can be injected in LoggedInGraph.
@GraphExtension(LoggedInScope::class)
interface LoggedInGraph {
val userRepository: UserRepository
@ContributesTo(AppScope::class)
@GraphExtension.Factory
interface Factory {
fun createLoggedInGraph(): LoggedInGraph
}
}
In the :app module:
@DependencyGraph(AppScope::class)
interface AppGraph
The generated code will modify AppGraph to implement LoggedInGraph.Factory and implement createLoggedInGraph() using a generated final LoggedInGraphImpl class that includes all contributed bindings, including UserRepository from :user-data.
interface AppGraph
// modifications generated during compile-time
interface AppGraph : LoggedInGraph.Factory {
override fun createLoggedInGraph(): LoggedInGraph {
return LoggedInGraphImpl(this)
}
// Generated in IR
class $$MetroGraph : AppGraph {
class LoggedInGraphImpl(appGraph: $$MetroGraph) : LoggedInGraph {
// ...
}
}
}
Finally, you can obtain a LoggedInGraph instance from AppGraph since it now implements LoggedInGraph.Factory:
// Using the asContribution() intrinsic
val loggedInGraph = appGraph.asContribution<LoggedInGraph.Factory>().createLoggedInGraph()
// Or if you have IDE support enabled
val loggedInGraph = appGraph.createLoggedInGraph()
Graph arguments¶
You can pass arguments to the graph via the factory:
@ContributesTo(AppScope::class)
@GraphExtension.Factory
interface Factory {
fun create(@Provides userId: String): LoggedInGraph
}
This maps to:
// Generated in IR
@DependencyGraph(LoggedInScope::class)
class LoggedInGraphImpl(
parent: AppGraph,
@Provides userId: String
): LoggedInGraph {
// ...
}
In AppGraph, the generated factory method looks like:
// Generated in IR
override fun create(userId: String): LoggedInGraph {
return LoggedInGraphImpl(this, userId)
}
Warning
Abstract factory classes cannot be used as graph contributions.
Contributed graphs may also be chained.
Binding Containers¶
Binding containers are classes, objects, or interfaces annotated with @BindingContainer that contain binding declarations (@Provides or @Binds) but are not themselves complete dependency graphs. They’re analogous to Dagger’s @Module annotation and can be used in cases where defining bindings in an (extended) interface is unwieldy or not helpful.
Unlike graphs and other @Includes types, their public accessors are not read. Only @Binds and @Provides declarations are read.
Tip
Binding containers can be seen as partial graphs and are intended to be reusable, composable units that are included in a complete graph.
Including via @Includes Parameters¶
The most flexible way to include binding containers is via @Includes-annotated parameters on graph factories.
@BindingContainer
class NetworkBindings(private val baseUrl: String) {
@Provides fun provideHttpClient(): HttpClient = HttpClient(baseUrl)
}
@DependencyGraph
interface AppGraph {
val httpClient: HttpClient
@DependencyGraph.Factory
interface Factory {
fun create(@Includes networkBindings: NetworkBindings): AppGraph
}
}
This allows you to bring any instance to the graph with its own internal logic.
Including via @DependencyGraph.bindingContainers¶
For simple binding containers, you can declare them directly in the graph annotation:
@BindingContainer
object NetworkBindings {
@Provides fun provideHttpClient(): HttpClient = HttpClient()
}
@DependencyGraph(bindingContainers = [NetworkBindings::class])
interface AppGraph {
val httpClient: HttpClient
}
This method works for:
objectclassesinterfaceorabstract classtypes with only@Bindsproviders or companion object@Providesproviders- Simple classes with a public, no-arg constructor
Chaining Binding Containers¶
Binding containers can include other binding containers using the includes parameter:
@BindingContainer
object CacheBindings {
@Provides fun provideHttpCache(): Cache = Cache()
}
@BindingContainer(includes = [CacheBindings::class])
object NetworkBindings {
@Provides fun provideHttpClient(cache: Cache): HttpClient = HttpClient(cache)
}
@DependencyGraph(bindingContainers = [NetworkBindings::class])
interface AppGraph {
val httpClient: HttpClient
}
The transitive closure of all included binding containers will be included in the final consuming graph.
Contributing Binding Containers¶
Binding containers can be contributed to scopes via @ContributesTo:
@ContributesTo(AppScope::class)
@BindingContainer
object NetworkBindings {
@Provides fun provideHttpClient(): HttpClient = HttpClient()
}
@DependencyGraph(AppScope::class)
interface AppGraph {
val httpClient: HttpClient
}
They can also replace other contributed binding containers:
// In a test variant
@ContributesTo(AppScope::class, replaces = [NetworkBindings::class])
@BindingContainer
object FakeNetworkBindings {
@Provides fun provideFakeHttpClient(): HttpClient = FakeHttpClient()
}
Graphs may exclude contributed containers:
@DependencyGraph(AppScope::class, excludes = [NetworkBindings::class])
interface AppGraph {
val httpClient: HttpClient
}
Notes¶
- Companion objects, annotation classes, and enum classes/entries cannot be annotated with
@BindingContainer. - Provides within a binding container’s companion object are automatically included.
- Enclosing classes of
@Bindsor@Providesproviders don’t need to be annotated with@BindingContainerfor Metro to process them - the annotation is primarily for reference to@DependencyGraph.Factoryand the ability to useincludes. - Binding containers may also be contributed.
- See #172 for more details.
Dynamic Graphs¶
Dynamic graphs are a powerful feature of the Metro compiler that allow for dynamically replacing bindings in a given graph. To use them, you can pass in a vararg set of binding containers to the createDynamicGraph() and createDynamicGraphFactory() intrinsics.
@DependencyGraph
interface AppGraph {
val message: String
@Provides fun provideMessage(): String = "real"
}
class AppTest {
val testGraph = createDynamicGraph<AppGraph>(FakeBindings)
@Test
fun test() {
assertEquals("fake", testGraph.message)
}
@BindingContainer
object FakeBindings {
@Provides fun provideMessage(): String = "fake"
}
}
The compiler will dynamically generate a hidden graph impl within the enclosing class or file that is unique to the combination of input [containers] and target type [T].
Constraints
- All containers must be instances (or objects) of binding containers.
- It’s an error to pass no containers.
- All containers must be non-local, canonical classes. i.e., they must be something with a name!
- This overload may be called in a member function body, top-level function body, or property initializer.
- The target [T] graph must be annotated with
@DependencyGraphand must be a valid graph on its own.
Implementation Notes
- The bulk of this implementation is in
IrDynamicGraphGenerator. - The generated graph impl is a private nested (static) class of the enclosing class or file.
- This doesn’t swap bindings in a real graph or use a real graph at all, instead tracking available dynamic bindings and preferring them when constructing a graph in
BindingGraphGenerator.
General Implementation Notes¶
Dependency graph code gen is designed to largely match how Dagger components are generated.
- Internal graph validation uses Tarjan’s algorithm + topological sort implementation.
- This runs in O(V+E) time
- The returned ordered list of bindings can be used to determine provider field generation order.
- Any binding whose order depends on one later in the returned order implicitly requires use of
DelegateFactory. - Dependencies are traversed from public accessors and
inject()functions. - Metro generates Provider Factory classes for each provider. These should be generated at the same time that the provider is compiled so that their factory classes. This is for two primary purposes:
- They can be reused to avoid code duplication
- Metro can copy default values for provider values over to the generated factory to support optional dependencies. Since default values may refer to private references, we must generate these factories as nested classes.
- Metro generates a graph impl class that holds all aggregated bindings and manages scoping.
- Scoped bindings are stored in provider fields backed by
DoubleCheck. - Reused unscoped providers instances are stored in reusable fields.
@Providesfactory parameters are stored in a field backed byInstanceFactory.- Multibindings create new collection instances every time.
- Multibinding providers are not accessible as standalone bindings.
- Graph extensions are implemented via a combination of things
- Custom
MetroMetadatais generated and serialized into Kotlin’sMetadataannotations. - Extendable parent graphs opt-in to generating this metadata. They write information about their available provider and instance fields, binds callable IDs, parent graphs, and provides callable IDs.
- Extendable parent graphs generate
_metroAccessor-suffixedinternalfunctions that expose instance fields and provider fields. - Child graphs read this metadata and look up the relevant callable symbols, then incorporating these when building its own binding graph.
- Custom
Optimizations¶
Metro applies several optimizations to generated graph code to reduce class size and improve runtime performance.
Unused binding elimination¶
By default, Metro removes bindings that are not reachable from any accessor or member injector function. This reduces the size of generated code and avoids unnecessary initialization work.
@DependencyGraph
interface AppGraph {
val httpClient: HttpClient // This is a root - it's reachable
fun inject(memberInjectedClass: MemberInjectedClass) // This is also a root
@Provides fun provideHttpClient(): HttpClient = HttpClient()
// This binding is NOT reachable from any accessor, so it will be eliminated
@Provides fun provideUnusedService(): UnusedService = UnusedService()
}
This can be disabled via metro.shrinkUnusedBindings=false if you need all declared bindings to be generated (e.g., for debugging).
Property collection¶
Not all bindings need dedicated provider fields. Metro analyzes the binding graph to determine which bindings require properties and what kind:
Scoping: Scoped bindings (e.g. @SingleIn) always get a field backed by DoubleCheck to ensure lazy, thread-safe instantiation that is a singleton within the enclosing graph.
Reference counting: Unscoped bindings used only once are inlined at their call site. Bindings used two or more times get a reusable provider field to avoid duplicate instantiation logic.
Alias resolution: When counting references, Metro follows @Binds alias chains to the final implementation. If Api binds to ApiImpl, references to Api count toward ApiImpl’s ref count.
Multibinding source accessors: Bindings contributed to multibindings (@IntoSet, @IntoMap) that have dependencies are extracted into getter properties. This avoids duplicating dependency resolution code at each multibinding collection site and avoids risking MethodTooLargeException issues at compile-time.
Chunking¶
JVM methods have a size limit. For graphs with many bindings, the constructor initialization code can exceed this limit. To avoid this, Metro splits initialization into multiple private init functions if necessary, each handling a subset of bindings.
// Generated structure for a large graph:
class AppGraph$Impl : AppGraph {
private val provider1: Provider<...>
private val provider2: Provider<...>
// ... hundreds more ...
init {
init1()
init2()
// ...
}
private fun init1() {
provider1 = ...
provider2 = ...
// ... up to statementsPerInitFun statements ...
}
private fun init2() {
// ... next batch ...
}
}
Configuration
| Gradle Extension Property | Gradle/System Property | Compiler Option | Description |
|---|---|---|---|
| statementsPerInitFun | metro.statementsPerInitFun |
statements-per-init-fun |
Max statements per init function (default: 25) |
Sharding¶
For very large graphs, even chunking may not be enough — the class itself can exceed JVM’s class file size limits. Sharding moves initialization logic into inner shard classes, distributing the code across multiple class files while keeping provider fields on the main graph class.
// Generated structure with sharding:
class AppGraph$Impl : AppGraph {
// Provider fields stay on the main class
private val repoProvider: Provider<Repository>
private val apiProvider: Provider<ApiService>
// ... many more ...
// Shards hold initialization logic
private inner class Shard1 {
fun initialize() {
repoProvider = provider { Repository.MetroFactory.create() }
apiProvider = provider { ApiService.MetroFactory.create(graph.repoProvider) }
}
}
private inner class Shard2 {
fun initialize() {
// ... next batch of initializations ...
}
}
init {
Shard1().initialize()
Shard2().initialize()
}
}
Sharding respects required binding initialization order and keeps strongly connected components (valid cycles broken by Provider/Lazy) together in the same shard.
Configuration
| Gradle Extension Property | Gradle/System Property | Compiler Option | Description |
|---|---|---|---|
| enableGraphSharding | metro.enableGraphSharding |
enable-graph-sharding |
Enable/disable sharding (default: true) |
| keysPerGraphShard | metro.keysPerGraphShard |
keys-per-graph-shard |
Max bindings per shard (default: 2000) |
Switching Providers¶
Switching providers are an optimization in graph generation that defers class loading. This can reduce graph initialization time by deferring bindings’ class init until it’s actually requested.
This is analogous to Dagger’s fastInit option.
You should really only use this if you’ve benchmarked it and measured a meaningful difference, as it comes with the same tradeoffs (always holding a graph instance ref, etc.)
Switching providers also support suspend providers.
// The graph
@DependencyGraph(AppScope::class)
interface AppGraph {
@Provides @SingleIn(AppScope::class) fun provideString(): String = "Hello, world!"
@Provides @SingleIn(AppScope::class) fun provideInt(string: String): Int = string.length
val stringLength: Int
}
// Generated structure for a graph with switching providers
class AppGraph$Impl : AppGraph {
private val provider1: Provider<String> DoubleCheck.provider(SwitchingProvider<String>(this, 0))
private val provider2: Provider<Int> DoubleCheck.provider(SwitchingProvider<Int>(this, 1))
@Provides
private class SwitchingProvider<T>(private val graph: Impl, private val id: Int) : Provider<T> {
override operator fun invoke(): T {
when (id) {
0 -> StringFactory.newInstance(...) as T
1 -> IntFactory.newInstance(graph.provider1()) as T
}
}
}
}
Configuration
| Gradle Extension Property | Gradle/System Property | Compiler Option | Description |
|---|---|---|---|
| enableSwitchingProviders | metro.enableSwitchingProviders |
enable-switching-providers |
Enable/disable switching providers (default: false) |