views:

277

answers:

1

I am building a Prism 2.1 demo by way of getting up to speed with the technology. I am having a problem with CompositePresentationEvents published and subscribed via the Event Aggregation service. The event subscription works fine if I set a strong reference (KeepSubscriberReferenceAlive = true), but it fails if I set a weak reference (KeepSubscriberReferenceAlive omitted).

I would like to subscribe with a weak reference, so that I don't have to manage unsubscribing from the event. Is there any way to do that? Why is a strong reference required here? Thanks for your help!

Here are the particulars: My demo app is single-threaded and has two regions, Navigator and Workspace, and three modules, NavigatorModule, WorkspaceAModule, and WorkspaceBModule. The NavigatorModule has two buttons, 'Show Workspace A' and 'Show Workspace B'. When one of these buttons is clicked, an ICommand is invoked that publishes a CompositePresentationEvent called ViewRequested. The event carries a string payload that specifies which workspace module should be shown.

Here is the event declaration, from the app's Infrastructure project:

using Microsoft.Practices.Composite.Presentation.Events;

namespace Prism2Demo.Common.Events
{
    public class ViewRequestedEvent : CompositePresentationEvent<string>
    {
    }
}

Here is the event publishing code, from the Navigator module:

// Publish ViewRequestedEvent
var eventAggregator = viewModel.Container.Resolve<IEventAggregator>();
var viewRequestedEvent = eventAggregator.GetEvent<ViewRequestedEvent>();
viewRequestedEvent.Publish(workspaceName);

Here is the event subscription code, which each Workspace module includes in its Initialize() method:

// Subscribe to ViewRequestedEvent
var eventAggregator = m_Container.Resolve<IEventAggregator>();
var viewRequestedEvent = eventAggregator.GetEvent<ViewRequestedEvent>();
viewRequestedEvent.Subscribe(this.ViewRequestedEventHandler, ThreadOption.PublisherThread, true);

The Subscribe() statement is shown with a strong reference.

Thanks again for your help.

A: 

A couple of things to check:

Make sure that your EventAggregator instance is being correctly registered with the container or it may itself be garbage collected:

container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager());

Also make sure that you have a strong reference to the subscribed object held somewhere (this in your subscription code).

GraemeF
Thanks, Graeme. I'm not sure I follow about the string reference to the subscribed object. Could you expand a little, and maybe provide a sample line of code? Thanks again.
David Veeneman
Make that a "strong reference" - sorry about that!
GraemeF
I just mean make sure that the subscriber object isn't itself being collected (I'm sure you already have :)
GraemeF