Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Viewmodel instantiated multiple times using ViewModelLocator (dependency container Transient)

$
0
0

Hi,

Using a viewmodellocator in the page(s) XAML, creates a new view model by using a decency container and resolving the viewmodel.
Everything is working as expected except for the part of pushing a newly created page on the navigation stack by using our NavigateToPageAsync() method.

The Navigation.PushAsync(page, true) has the effect of asking the viewmodellocator for a viewmodel and so a new viewmodel is created. Now I have 2 viewmodels. If we use Navigation.PushModelAsync() however, we do not see the effect of another viewmodel being created.

Reading https://forums.xamarin.com/discussion/49257/view-model-instantiating-multiple-times I understand that when removing the BindingContext from the XAML and moving this to the code behind of the Page, I have a solution to the problem.

The reason the viewmodellocator returns a new viewmodel every time (Transient) the property is read, is that I rather not have a direct reference to the viewmodel because the memory of this viewmodel and injected services/repositories will not be released automatically. Checked this by using Finalizers and the dispose method.

For better understanding, little pieces of code :

Viewmodellocator

public CarsViewModel CarsVIewModel
{
    get
    {
        return _dependencyContainer.Resolve<CarsViewModel>();
    }
}
RegisterViewModels()
{
    _dependencyContainer.RegisterType<CarsViewModel>();
}

CarsPage

BindingContext=“{Binding CarsViewModel, Source={StaticResource ViewModelLocator}}"

NavigationService

NavigateToPageAsync(....)
{
    var page = Actvator.CreateInstance(type) as BasePage;
    await (page.BindingContext as BaseEventsViewModel).Initialize();
    await (page.BindingContext as BaseEventsViewModel).LoadDataAsync();
    await Navigation.PushAsync(page, true);
}

Love to hear!


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>