I use Prism 5.0, and I have trouble configuring it to reuse existing views. Whenever IRegionManager.RequestNavigate(string regionName, Uri source)
is called, it creates a new view instead of using the view that was previously created. Strangely, CLRProfiler also indicates that Prism's region manager holds on to references to all the previously created view instances, leading to a memory leak.
My view models implement INavigationAware
, and return true
in IsNavigationTarget()
but the method is never called. I tried implementing it on the view as well with the same result.
As a test, I implemented IActiveAware
on the view, which shows that it is deactivated as soon as I navigate to another view (I'm not sure this is relevant).
I found this question: PRISM WPF - Navigation creates new view every time but my V-VM naming conventions match those of the answer (I use AutoFac, by the way).
I've only found a workaround: removing the active view from the region using NavigationContext.NavigationService.Region.Remove()
in the view model's INavigationAware.OnNavigatedFrom()
implementation. When I do this, Prism's region manager releases the reference to the view. This works but it seems inefficient to always recreate the view when it is needed.
Almost all the related questions on SO ask how to create a new view on a navigation event, so I assume the default behavior is that views are reused. I need pointers here.
EDIT
We use AutoFac's AutofacExtensions.RegisterTypeForNavigation<T>(this ContainerBuilder builder, string name = null)
to register the views. We do use IRegionManager.RequestNavigate()
for navigation between views. INavigationAware
is implemented on the ViewModels. However, while INavigationAware.OnNavigatedTo()
and OnNavigatedFrom()
are called, IsNavigationTarget()
is never called (the latter is not called even if the views implement INavigationAware
).
I can detect that a new view is created by setting a breakpoint in the ctor of the view. A CLRProfiler heap dump also shows that the region manager has as many instances of the view as many times it has been navigated to. The ViewModels are only created once, as they are registered with AutoFac as single-instance.
As a temporary measure, we made the Views implement IRegionMemberLifetime
, where KeepAlive
returns false
. This is not very effective, as the views are recreated every time they are needed but it prevents the region manager from holding on to previous views.