IgorShare Thoughts and Ideas

Consulting and Training

Retrieving a ShellContainer from Unity

Posted by Igor Moochnick on 09/01/2008

As I’ve mentioned in my previous post Hosted Prism, that you can add dynamically a Shell Container to your application. This time I’m going to show you how you can configure this container dynamically and have a possibility to replace it at any time without changing your code.

To do so I’m going to use a configuration file. It’s up to you to decide which one. You can use App.config, but I’ll recommend to have a separate file for your IOC, so the customers will not be exposed to a lot of nose and will not change stuff accidentally.

Create a config file (use any name you wish with .config extension – I’ll explain why in a different post).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <typeAliases>

      <!-- Lifetime manager types -->
      <typeAlias alias="singleton"
           type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
               Microsoft.Practices.Unity" />

      <!-- User-defined type aliases -->
      <typeAlias alias="UIElement" type="System.Windows.UIElement, PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      <typeAlias alias="Shell" type="OwlHollowLib.ShellContainer, OwlHollowLib" />

    </typeAliases>

    <containers>
      <container name="global">
        <types>
          <type name="Shell" type="UIElement" mapTo="Shell">
	<lifetime type="singleton" />
          </type>
        </types>
      </container>
    </containers>
  </unity>

</configuration>

Note that in the “container[@name=”global”]” I’m associating the “ShellContainer” user control with the type “UIElement” and assigning a “Shell” name for this object. As well I’m marking this object to be a singleton, but this is not necessary if you need more than one ShellContainer in your application.

And this is how you can get a reference to the ShellContainer:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        try
        {
            var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "MyApplication.config" };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

            var section = (UnityConfigurationSection) configuration.GetSection("unity");

            IUnityContainer container = new UnityContainer();
            section.Containers["global"].Configure(container);

            var shellElement = container.Resolve<UIElement>("Shell");

            this.mainGrid.Children.Add(shellElement);
        }
        catch(Exception e)
        {
            System.Diagnostics.Trace.WriteLine(e.ToString());
        }
    }
}

As you can see, you need to initialize UnityContainer from a config file. If you are using a standard App.config file – you don’t need to create an ExeConfigurationMap.

As soon as the UnityContainer is initialized – it’s available for you to start resolving objects and types. The trick in the code above is to resolve your components by their parent types and by an associated name. You can see it in the line #17. This will allow you in the future to replace one UIElement with another without recompiling the application.

Note: DO NOT use the same name (in quotes) as an existing class. The resolution doesn’t work! It looks like the default resolving is conflicted with the resolve-by-name operation.

The technique described above allows you to decouple your modules and create … a loosely coupled but cohesive application.

If you want to take this technique to the extreme and make Unity calls from WPF, you can check the series of posts by Denis Vuyka [Injecting Xaml with Unity Application Block using Markup Extensions].

Stay tuned for more Prism and Unity posts.

Advertisements

One Response to “Retrieving a ShellContainer from Unity”

  1. Thanks for the feedback

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: