09.04.2018 Views

tornadofx-guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Dependency Injection<br />

Dependency Injection<br />

View and Controller are singletons, so you need some way to access the instance of a<br />

specific component. Tornado FX supports dependency injection, but you can also lookup<br />

components with the find function.<br />

val myController = find(MyController::class)<br />

When you call find , the component corresponding to the given class is looked up in a<br />

global component registry. If it did not exist prior to the call, it will be created and inserted<br />

into the registry before the function returns.<br />

If you want to declare the controller referance as a field member however, you should use<br />

the inject delegate instead. This is a lazy mechanism, so the actual instance will only be<br />

created the first time you call a function on the injected resource. Using inject is always<br />

prefered, as it allows your components to have circular dependencies.<br />

val myController: MyController by inject()<br />

Third party injection frameworks<br />

TornadoFX makes it easy to inject resources from a third party dependency injection<br />

framework, like for example Guice or Spring. All you have to do is implement the very simple<br />

DIContainer interface when you start your application. Let's say you have a Guice module<br />

configured with a fictive HelloService . Start Guice in the init block of your App class<br />

and register the module with TornadoFX:<br />

val guice = Guice.createInjector(MyModule())<br />

FX.dicontainer = object : DIContainer {<br />

override fun getInstance(type: KClass)<br />

= guice.getInstance(type.java)<br />

}<br />

The DIContainer implementation is configured to delegate lookups to<br />

guice.getInstance<br />

To inject the HelloService configured in MyModule , use the di delegate instead of the<br />

inject delegate:<br />

265

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!