Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How Does MEFedMVVM Compose the Catalogs and How Can I Override the Behavior? - MEFedMVVM Part 4

DZone's Guide to

How Does MEFedMVVM Compose the Catalogs and How Can I Override the Behavior? - MEFedMVVM Part 4

·
Free Resource

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.

public interface IComposer
{
bool InitializeContainer();
}

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

AggregateCatalog aggregateCatalog = new AggregateCatalog();

//add the catalogs for the current assembly and the MEFedMVVM assembly since we are overriding the default behavior
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ViewModelLocator).Assembly));
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));
var listOfPluginXAPs = new[] { "Plugin1.xap" };

foreach (var item in listOfPluginXAPs)
{
DeploymentCatalog deploymentCatalog =
new DeploymentCatalog(item);

aggregateCatalog.Catalogs.Add(deploymentCatalog);

deploymentCatalog.DownloadCompleted += (s, args) =>
{
if (args.Error != null)
Debug.WriteLine("Error downloading plugin from " + item + " Exception: " + args.Error);
if (args.Cancelled)
Debug.WriteLine("Downloading of plugins was cancelled");

PluginsDownloaded = true;
};

deploymentCatalog.DownloadAsync();
}

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.

var catalog = new AggregateCatalog();
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var extensionPath = String.Format(@"{0}\Extensions\", baseDirectory);
catalog.Catalogs.Add(new DirectoryCatalog(baseDirectory));
catalog.Catalogs.Add(new DirectoryCatalog(baseDirectory, "*.exe"));
if (Directory.Exists(extensionPath))
catalog.Catalogs.Add(new DirectoryCatalog(extensionPath));
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

var provider = new ExportFactoryProvider();
var container = new CompositionContainer(catalog, provider);
provider.SourceProvider = container;
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/

 

Topics:

Published at DZone with permission of Marlon Grech. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}