-
Notifications
You must be signed in to change notification settings - Fork 271
Dependency Injection
Wiki ▸ Documentation ▸ 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()
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