capture events in Shell?

Topics: Prism v4 - WPF 4
May 5, 2011 at 1:39 AM

Just wondering what code I'd use to inject IEventAggregator into the Shell? ie in the bootstrapper

 

thanks

Developer
May 5, 2011 at 2:57 PM
Edited May 5, 2011 at 2:58 PM

Hi,

In order to obtain a reference of the Event Aggregator (or any other service that has been made available through a dependency injection container), you should resolve it through the dependency injection mechanism you're using. For example, supposing you use constructor injection, if you're using unity you should do something like this:

 

public Shell(IEventAggregator eventAggregator)

{

(...)

eventAggregator.GetEvent<SomeEvent>().Subscribe(Handler);

(...)

}

 

And if you're using MEF, it would look like this:

 

[ImportingConstructor]
public Shell(IEventAggregator eventAggregator)

{

(...)

eventAggregator.GetEvent<SomeEvent>().Subscribe(Handler);

(...)

}

 

Note that this is possible only if you compose your shell in the CreateShell or InitializeShell method through the container (which is the default case in Prism applications). The following code from the Bootstrapper in the HelloWorld QuickStart (and it's MEF equivalent) might help illustrate this:

 

class Bootstrapper : UnityBootstrapper
    {

(...)
       protected override DependencyObject CreateShell()
        {
            return this.Container.Resolve<Shell>();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();

            App.Current.MainWindow = (Window)this.Shell;
            App.Current.MainWindow.Show();
        }   

(...)

    }

and with MEF:

 

class Bootstrapper : MefBootstrapper
    {

(...)
       protected override DependencyObject CreateShell()
        {
            return this.Container.GetExportedValue<Shell>();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();

            App.Current.MainWindow = (Window)this.Shell;
            App.Current.MainWindow.Show();
        }   

(...)

    }

You might find the following chapter from the Prism MSDN documentation useful:

Chapter 3: Managing Dependencies Between Components

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi

May 6, 2011 at 6:42 AM

this works perfectly, thanks!