How does MEFedMVVM compose the catalogs and how can I override the behavior? – MEFedMVVM Part 4

Some content may be out of date. See latest blog on changes made here.

Introduction

As you already know, MEFedMVVM is capable of composing the catalogs for you so that you do not have to worry about it both in Silverlight and in WPF. The composition happens a bit differently in SL and WPF so I will divide the “How to write a composer” section in 2, how it works for SL and how it works for WPF. But first let’s see what is common.

Please Note: This article is for advanced scenarios of using MEFedMVVM if you are using MEFedMVVM with its default behavior you do not need to do this since by default MEFedMVVM does the composition on its own. Yet if you want to have a silverlight app that uses multiple XAP files or a WPF app that is loading dlls that are not referenced by the main application and that reside somewhere else then the exe directory (or even Extensions folder of the base directory).

The LocatorBootstrapper and the IComposers

If you have been looking in the code of MEFedMVVM you’ll know that there is a class called LocatorBootstrapper. This class is responsible of checking if the MEF composition is done and if not I will ask the Composers to do so.

The “Composers” ? What the hell are these??

Basically these are instances of IComposer and there are 2 of these in the LocatorBootstrapper, one for DesignTime composition and one for Runtime. By default MEFedMVVM uses its own implementation of the IComposer which are DefaultRuntimeComposer and DefaultDesignTimeComposer but if you want to do something smarter (I will talk more on this later in the article) you can call the ApplyComposer method of the LocatorBootstrapper and inject a runtime composer that you implement. You must make sure to make this call before anything gets composed. A good place to do this is in the Application class constructor.

In the current version you cannot supply a DesignTime IComposer. I could have made the ApplyComposer API to accept another composer for DesignTime yet this method would be called always too late from Blend. I am currently working on a solution for this. Having said this, I do not see why you would want to override the default DesignTime composer since you still have control. I will talk more on this later in the post but any assembly marked with the DesignTimeCatalog will get picked up and loaded by the DefaultDesignTimeComposer. The only case where you would want to override this behavior is if you want to ignore the DesignTimeCatalog attribute. This is not suggested since not only it will slow down a lot the composition since blend loads many assemblies but it can also cause exceptions in Silverlight. I am open for suggestions so if you have any please let me know.

How can I create a Composer?

You do so by implementing the IComposer interface which looks like this.

   1: public interface IComposer

   2:     {

   3:         bool InitializeContainer();

   4:     }

In the InializeContainer you should put the code to initialize the Container and call CompositionHost.Initialize. (For WPF there is a catch that I will explain in the WPF section of the post).

Understanding and writing a Composer for Silverlight

What do the default MEFedMVVM composer do for SL?

The DesignTimeComposer will load all the assemblies that are decorated with the DesignTimeCatalog attribute in the AppDomain of Blend by using a trick explained here and create a CompositionContainer with MEF AssemblyCatalogs. So even if you have multiple XAP files MEFedMVVM will still get resolved as long as you put the DesignTimeCatalog attribute. If you forget to do this MEFedMVVM will put a message in the output window saying “No assemblies found for Design time. Quick tip… do not forget to put the DesignTimeCatalogAttribute for the assembly that contains your design time stuff. Even if its just a ViewModel you want to load.”. Yet in order to get this you need to have Blend attached with VisualStudio. (I am working hard on a solution to make this more obvious).

The Runtime Composer does not do anything. No really! It does not. The implementation simple returns true in the InitializeContainer method. This is because in SL CompositionInitializer.SatisfyImports (a class that is not present in WPF since WPF does not have System.ComponentModel.Composition.Initialization.dll) will create a container from the existing XAP.

So if you want to override the Runtime behavior for the SL version of MEFedMVVM you do not even have to call LocatorBootstrapper.ApplyComposer because for SL this is not doing anything anyway! But for the code to be the same for SL and WPF maybe its best if you do the call.

Quick Tip: If you are overriding the default container do not forget to add the an assembly catalog for the MEFedMVVM library, if you want to get injected with services that come out of the box with MEFedMVVM such as IVisualStateManager. Here is some sample code that is loading different XAP files

   1: AggregateCatalog aggregateCatalog = new AggregateCatalog();

   2: //add the catalogs for the current assembly and the MEFedMVVM assembly since we are overriding the default behavior

   3: aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ViewModelLocator).Assembly));

   4: aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));

   5: var listOfPluginXAPs = new[] { "Plugin1.xap" };

   6: foreach (var item in listOfPluginXAPs)

   7: {

   8:     DeploymentCatalog deploymentCatalog =

   9:       new DeploymentCatalog(item);

  10:  

  11:     aggregateCatalog.Catalogs.Add(deploymentCatalog);

  12:  

  13:     deploymentCatalog.DownloadCompleted += (s, args) =>

  14:     {

  15:         if (args.Error != null)

  16:             Debug.WriteLine("Error downloading plugin from " + item + " Exception: " + args.Error);

  17:         if (args.Cancelled)

  18:             Debug.WriteLine("Downloading of plugins was cancelled");

  19:  

  20:         PluginsDownloaded = true;

  21:     };

  22:  

  23:     deploymentCatalog.DownloadAsync();

  24: }

  25: CompositionHost.Initialize(aggregateCatalog);

Understanding and writing a Composer for WPF

What do the default MEFedMVVM composer do for WPF?

The DesignTimeComposer will load all the assemblies that are decorated with the DesignTimeCatalog attribute and create an AssemblyCatalog for each one. If you forget to put the DesignTimeCatalog attribute MEFedMVVM will put a message in the output window saying “No assemblies found for Design time. Quick tip… do not forget to put the DesignTimeCatalogAttribute for the assembly that contains your design time stuff. Even if its just a ViewModel you want to load.”. Yet in order to get this you need to have Blend attached with VisualStudio. (I am working hard on a solution to make this more obvious).

The RuntimeComposer will create a DirectoryCatalog for the AppDomain base directory and also checks if there is an Extensions folder and if so it will create a DirectoryCatalog for that folder as well. So yea if you have a set of plugins that are not being referenced by the main application, you do not even need to override the default behavior since you can make the plugins compile in an Extensions folder and MEFedMVVM will still load those assemblies. This is the code that creates the MEF catalog for the Default WPF Runtime Composer.

   1: var catalog = new AggregateCatalog();

   2: var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

   3: var extensionPath = String.Format(@"{0}\Extensions\", baseDirectory);

   4: catalog.Catalogs.Add(new DirectoryCatalog(baseDirectory));

   5: catalog.Catalogs.Add(new DirectoryCatalog(baseDirectory, "*.exe"));

   6: if (Directory.Exists(extensionPath))

   7:     catalog.Catalogs.Add(new DirectoryCatalog(extensionPath));

   8: return catalog;

The “catch” with WPF version of MEFedMVVM

WPF does not have System.ComponentModel.Composition.Inialization so as such it does not have CompositionHost and CompositionInitializer but Mr.MEF, Glenn Block created this dll for us over here, and we are using it in MEFedMVVM, thus we benefit from the same code for SL and WPF. The only difference is that you have to do a trick when creating the CompositionContainer. You need to specify the ExportFactoryProvider when creating the CompositionContainer. like so

   1: var provider = new ExportFactoryProvider();

   2: var container = new CompositionContainer(catalog, provider);

   3: provider.SourceProvider = container;

   4: CompositionHost.Initialize(container);

If you fail to do so MEFedMVVM will not resolve the ViewModels and the Services since MEFedMVVM using ExportFactory to get the imports.

Enough talking (well as such its blogging 🙂 ) give us some code!

I did 2 samples one for Silverlight by using DeploymentCatalog to load assemblies from different xap files and one for WPF using DirectoryCatalog to load plugins from a folder called Plugins (this was just to show how you can do it because as such I could made the plugins compile in a Directory called Extensions and it would still have worked).

The source can be found in by download the code from http://mefedmvvm.codeplex.com/SourceControl/list/changesets there is a folder samples where you will find these 2 samples.

Conclusion

As you can see MEFedMVVM can also be used in more advanced scenarios where you want control over the MEF Composition of Catalogs. The default composition will work for most of the apps, yet for some (such as multiple XAP SL applications) you must have control over the composition.

As always feedback is much appreciated.

Download MEFedMVVM and start MEFing it up!

http://mefedmvvm.codeplex.com/

9 thoughts on “How does MEFedMVVM compose the catalogs and how can I override the behavior? – MEFedMVVM Part 4

  1. Pingback: Club Penguin fluG Reviews – December 2009 Clothing Catalog

  2. Pingback: How does MEFedMVVM compose the catalogs and how can I override the … | Source code bank

  3. Pingback: Dew Drop – April 27, 2010 | Alvin Ashcraft's Morning Dew

  4. Hello Marlon,

    I have installed the Blend4 RV software version in order to (re)test the “Blendability” capabilities

    The good : UsersScreen.xaml and MainWindow.xaml hmi are now well displayed for SL and WPF projects.
    The bad : whereas the UsersScreen’s DataContext project is well set (TestViewModel object class), I can not use it in the “DataBinding…” expression Blend window. The DataContext pane is empty !!

    Have you noticed this problem ?

  5. Dude,

    Try as I will, I’m unable to compile the MEFedMVVM project. The two errors that I get are related to your XmlnsDefinition stuff.

    What gives?

  6. Dude,

    Permit me to qualify the XmlnsDefinition. It’s in the assembly.cs file on line 39.

    Looking forward to your speedy reply.

  7. Pingback: An introduction to MEFedMVVM – PART 1 « C# Disciples

Leave a comment