简体   繁体   中英

Prism's Region Manager keeps objects alive

I am working on a WPF project. It uses the Prism's IOC container, RegionManager and EventAggregator.

I bind the views and view models with the autowire feature of Prism. So I navigate just with RegionName and view as below

    _regionManager.RequestNavigate(
                RegionName,
                NameOf(ParentContentView))

ParentContentView has 3 different child controls which comminucate with each others by using EventAggregator feature of the Prism. The program tries to load this ParentContentView from scratch every time.

ParentContentView has been registered to the our IOC as below

           builder.
            RegisterTypeForNavigation(Of ParentContentView)(
                Nameof(ParentContentView))

After leaving this ParentContentView by using regionmanager.RequestNavigate() method the ParentContentView is still alive. I inspected it on dotMemory application of JetBrains.

Every open and leave operation adds an object to the memory. For example if I open and close ParentContentView 4 times then object counts of ParentContentView will be 4. In a somehow prism keeps it alive.

I implemented IRegionMemberLifetime in View code behind and the code as below

public partial class ParentContentView : IRegionMemberLifetime
{
    public ParentContentView()
    {
        InitializeComponent();
    }

    public bool KeepAlive
        => false;
}

I debugged the code and it really hits KeepAlive property but it did not solve the problem. I also tried to remove the event references of child objects. I also unsubscribe the eventaggregator events. none of them did not work for me.

Any help would be appreciated.

Prism doesn't care for IDisposable on view models and leaves everything to the garbage collector by default.

You can look up which references exactly keep your objects alive (are they really kept alive or is the garbage collector just lazy because there's no pressure?), but it may be easier to make the view model IDisposable and use a region behavior to dispose them when they aren't needed anymore (see this issue ).

You can try to implement the INavigationAware interface by PRISM and see if that solves your problem. This will provide you with three methods, but the method of interest is the IsNavigationTarget method

IsNavigationTarget(NavigationContext navigationContext) 
{
}

If you return false, it will create a new instance of the View when you Navigate to it again.

If you return true, it will reuse the existing View when you Navigate to it. This is useful if you want to retain any information which has been filled in the View.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM