sialcasa / mvvmFX

an Application Framework for implementing the MVVM Pattern with JavaFX
Apache License 2.0
494 stars 104 forks source link

[scopes] @InjectScope vs @PostConstruct #403

Closed tfleis closed 8 years ago

tfleis commented 8 years ago

The scope is injected after PostConstruct annotated method is called. As workaround we use "public void initialize()" instead of PostContruct annotation.

manuel-mauky commented 8 years ago

Hi, this is a known limitation. It's the same for all other resources and classes that are injected by mvvmFX (like @InjectViewModel, @InjectRessourceBundle).

Using the public void initialize() method is the recommended way for initialization of ViewModels.

Some details to understand the reason for this behaviour: Internally the following steps are done when a ViewModel is requested:

  1. MvvmFX Viewloader request an instance of MyViewModel.class from DI container
  2. DI container creates an instance of the requested class
  3. DI container injects everything that is annotated with @Inject into that instance
  4. DI container calls @PostConstruct
  5. DI container hands over the instance to the ViewLoader
  6. ViewLoader injects everything that is handled by mvvmFX (like Scopes)
  7. ViewLoader call public void initialize() on the ViewModel

The postconstruct method is already called before we get the instance for the first time. By the way, this process is the reason why we need special annotations like @InjectScope instead of just using @Inject.

I can understand your feature request but at the moment there is no way of implementing it. At the moment the loading process is independ from a specific DI container. The ViewLoader simply asks whatever DI container is available for new instances (or creates it by itself if none is available). To implement this feature the ViewLoader would need to know which DI container is running at the moment and the loading would need to be DI container specific.

manuel-mauky commented 8 years ago

I've added a section for livecycles and post construct in the wiki.

tfleis commented 8 years ago

Hi Manuel,

thank you for the explanation. We will switch from @PostConstruct to public void initialize().

You can close this issue.