Skip to content
This repository has been archived by the owner on Sep 28, 2024. It is now read-only.

Dependency Injection

Edvin Syse edited this page Apr 14, 2016 · 7 revisions

WikiDocumentationDependency Injection

Dependency Injection

View and Controller are singletons, so you need some way to access the instance of a specific component. Tornado FX supports dependency injection, but you can also lookup components with the find function.

val myController = find(MyController::class)

When you call find, the component corresponding to the given class is looked up in a global component registry. If it did not exist prior to the call, it will be created and inserted into the registry before the function returns.

If you want to declare the controller referance as a field member however, you should use the inject delegate instead. This is a lazy mechanism, so the actual instance will only be created the first time you call a function on the injected resource. Using inject is always prefered, as it allows your components to have circular dependencies.

val myController: MyController by inject()

Third party injection frameworks

TornadoFX makes it easy to inject resources from a third party dependency injection framework, like for example Guice or Spring. All you have to do is implement the very simple DIContainer interface when you start your application. Let's say you have a Guice module configured with a fictive HelloService. Start Guice when your app starts and register the module with TornadoFX:

val guice = Guice.createInjector(MyModule())

FX.dicontainer = object : DIContainer {
    override fun <T : Any> getInstance(type: KClass<T>) 
        = guice.getInstance(type.java)
}

The DIContainer implementation is configured to delegate lookups to guice.getInstance

To inject the HelloService configured in MyModule, use the di delegate instead of the inject delegate:

val MyView : View() {
    val helloService: HelloService by di()
}

The di delegate accepts any bean type, while inject will only allow beans of type Injectable, which includes TornadoFX's View and Controller. This keeps a clean separation between your UI beans and any beans configured in the external dependency injection framework.

Next: Config

Clone this wiki locally