However, for the "common man", nuclear physics is only important because it makes your lights turn on when you flick the light switch. With MEF, we will use it to simply load a .xap file that contains a Silverlight application. Trust me, it can do a lot more, but MEF is in a state like the Visual State Manager was years ago, powerful but hard to use, so you may decide to wait for more advanced tooling to appear before implementing some of it's other functions.

A Quick Easy Win - For Those Having A Hard Time Understanding MEF

You may have heard about MEF and how great it is. However, you may find it a bit confusing and hard to follow. Fear not. This article is designed for you! The goal here is to give you a quick easy win. You will be able to understand this one. You will come away with something you can use, and you will be able to tell your fellow colleagues, "MEF? yeah I'm using that, good stuff".

A Little Help From My Friends - Glenn Block and Davide Zordan

This article covers material, and uses code, from Glenn Block and Davide Zordan. You will want to read their articles after this one because they go much deeper into what you can do with MEF. The difference with this article is that we will walk through all the steps and we will also use View Model Style for everything.

The Application

First, we add two Silverlight applications to the ClientBin directory of the web project for the Main Silverlight Project.

When you launch the Main Silverlight Project, you can select a Silverlight .xap from the dropdown, and click the Load button.

The .xap will be dynamically loaded.

Creating the "Injected" Silverlight Applications

We will first create two Silverlight applications. They will each produce a .XAP file that will be placed in the ClientBin directory of the Main Silverlight Project. The Main Silverlight project with then dynamically load them, and show them.

Open Microsoft Expression Blend 4, and select File then New Project (We are using Expression Blend because it has templates to easily create View Model style controls) all of this code will of course work with Visual Studio (I actually use Visual Studio to write all the code orginally).

Create a new Silverlight Application called InjectedApplication1

In the Projects window, right-click on References and select Add Reference...

Navigate to:

..\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\

Add references to:

System.ComponentModel.Composition.dll

System.ComponentModel.Composition.Initialization.dll

(you need these references, so we can add MEF attributes to the class, so the application can be recognized by MEF)

Additional Notes:

You don't need System.ComponentModel.Composition.Initialization.dll to be referenced by your Silverlight Applications (part assemblies) unless they are using CompositionInitializer.

For part assemblies you should set the MEF references (and other shared references) to be CopyLocal = false.

CopyLocal = false will keep the size of the XAPs down, it will also prevent duplicates

Deployment Catalog Service (COMPLICATED STUFF!)

We are now getting into the "complicated stuff". We are going to create a class that will actually load the .xap on demand. We will create an Interface for it's methods; AddXap and RemoveXap, and then we will implement the class (we are putting both in the same file to simply things, normally you would put your interface in it's own file).

Add a class to the HelperClasses folder called DeploymentCatalogService.cs.

Yes we could go into the details of "how" it does what it does, but that is covered in the links above. If you want to know "what" it does, it loads a requested .xap into a "catalog". The code we will cover next, pulls the .xap out of the catalog and loads it into the Main Silverlight Application.

Dynamically Downloading a Silverlight Application Using MEF

We will now create the View Model. It will basically perform the function in the diagram above.

Open up MainPageModel.cs and replace ALL the code with the following code:

We have reached the apex of the "complicated stuff". It's all downhill from here. There are links at the end of this article that will fully explain how the code above works. The general explanation is in the comments in the code.

We need to add the code "DeploymentCatalogService.Initialize()" to initialize the DeploymentCatalogService, for it to work.

Add the Silverlight Applications

When you look in the website project in the Projects window, you will only see the MainApplication.xap file in the ClientBin directory.

Drag and drop the InjectedApplication1.xap and InjectedApplication2.xap files into the directory.

Hit F5 to build and run the application.

You will be able to dynamically load each application.

Why Should You Use MEF To Dynamically Load Silverlight Applications ?

There are other ways to dynamically load a Silverlight .xap. I have a project (Introducing SilverlightDesktop.net) that does that. the problem I ran into, was handling the project dependencies. For example, if you use a control from the Silverlight Control Toolkit, it wont work. MEF will resolve any dependencies. This is really important when using View Model Style. A Designer could add a lot of custom Behaviors and other dependencies.

This is an example where using MEF is LESS code than if you used an alternative method (that provided the same powerful functionality). The hard part with MEF is putting the correct attributes in the correct places and setting their values properly. Hopefully this tutorial provided a helpful example.

There Is More To MEF

There is so much more to MEF, that this simple example is almost insulting to the technology. However, I fully expect Microsoft to create more tooling and example code to make it's implementation of it's other features easier in the future.

Comments and Discussions

All I can say is that the dynamically injected module IS now part of the application. The application sees it as code that is part of the application. So, whatever it was injected IN TO can have error handling that would operate normally.

In my example, when you click the Load button it calls "LoadXAP". Put a try catch around that and it should catch any errors when loading. After the module is loaded you would have to catch errors in "Application_UnhandledException" in "App.xaml.cs".

Hi, great tutorial. I tried to implement your example in a current project and I got an error when loading the XAP:

System.InvalidOperationException: The package downloaded successfully but an error occurred while reading the contents of the package. See the inner exception for more details. ---> System.ComponentModel.Composition.ChangeRejectedException: The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced multiple composition errors, with 2 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.

1) Change in exports prevented by non-recomposable import 'SLX.Navigation.ViewModels.DemosViewModel.CatalogService (ContractName="SLX.Business.Framework.IDeploymentCatalogService")' on part 'SLX.Navigation.ViewModels.DemosViewModel'.

2) Change in exports prevented by non-recomposable import 'SLX.Navigation.ViewModels.DemosViewModel.CatalogService (ContractName="SLX.Business.Framework.IDeploymentCatalogService")' on part 'SLX.Navigation.ViewModels.DemosViewModel'.

I ran through the debugger and I noticed that the following query returns null so no xap is getting loaded into the stack panel:

Thank for your great tutorial on MEF, it has helped me a lot with being new to SilverLight. I have managed to apply what I have learned from your tutorial to my project and its works great. However what I would like to do now is select a specific usercontrol inside an xap file.

Say I have a xap file called Reports.xap which has 3 user controls in it called Report1, Report2, Report3.

I assume that using the following with the the FirstOrDefault will get me the Report1, and if I change that to LastOrDefault it will get me Report3.

In my examples I only have one control in my .xap so I simply add the .xap contents to a page. If you have more controls in your .xap you should be able to reference them like you would if you were not using MEF, but I have no example code that I can point you to. Sorry.

Awesome article. I am finally starting to "get my head around" this MEF stuff. I have a question about debugging though. I went through your example and am getting the message for InjectedApplication1 but not for 2! I am not getting an error, which is good, but how do I go about debugging if one of the .xap files are not loading. Also looking forward to the MEF with Wcf RIA Services article as that is why I am learning this stuff. Again great job!

Ok, I found the mistake. As I say "user error". I forgot to modify MainPage.xaml.cs for InjectedApplication2. I knew it was my error because your download worked and I wanted to step through myself to be able to understand it.

Thanks for your time put into this article and many others. They are a big help in me learning this new stuff as I have a very large Enterprise level application I am architecting and between MEF, MVVM, PRISM, EF and all the new technologies, I am trying to figure the right fit for this app. Would love to hire you as a consultant however our parent company are in the dark ages (AS/400 applications and when they saw our MS Access/SQL Server app. they thought it was the greatest thing since sliced bread).

If you need more end to end examples. Meaning, you may use Prism because you feel you "have to". In my opinion, the "need" for Prism is actually small. I mean if you are making an app like Visual Studio with a bunch of teams working on each part, then yes you need it. But, if you are 2-3 people do you need that overhead when you could just pick up the phone and say "Hey Joe, I'm gonna a zip code to my control, can you add it to your search control?"

Thanks for the info. I am actually the sole developer at my location. Yes, the SQL DBA, the .NET Architect, Lead C# Developer, and all things application related. So, your comment about Prism was very helpfull. I know not to waste any time on it! Your RIATasks was next on my "hit list" of items to check out and I am going to have to check out LightSwitch. Geeze, something else to figure out and play with! Luckily I enjoy learning new stuff, however, being the only developer at my organization gets frustrating at times. Luckily I can figure anything out, but sometimes it takes me a long time and lots of hair pulling .

If we download additional (in addition to the main xap, that is) xap files, how do we make sure that they get updated when we upload new versions to the server? Is there a way to delete them on the client - programmatically?

Thanks for the excellent guidance. I read a lot of articles and watched many videos explaining MEF before finding this article and I have to say this was by far the easiest to understand of them all.

I have our project successfully loading the XAP files. However, the applications we are trying to modularize are all going to be using RIA Services and I was getting some exceptions regarding the WCF endpoint not being found. Some research revealed that we can specify the Uri of the service that's running when making an instance of our Domain Context to address this problem. Our idea to handle this instead of hard coding the Uri was to use RIA in the main site to get some application settings from the database that contains the Uri that needs to be used. We are pretty confident this would work for us, but wanted an opinion on whether or not this is the correct approach to take. Is there some other way to handle this situation that you would consider to be a simpler or better alternative?

I have an article that I am working on that uses web services but I think it's the same problem that you are describing. In the .xaps that ar being loaded into the main project, I had to put in this code in their code behind:

objDataContext.SetBaseAddress(GetBaseAddress()); causes a property called "BaseAddress" in my ViewModel to be set as the address of my web service. I use the value of that property when making web service calls.

If I do not use MEF I don't need that bit of code behind because I can put that code (that figures out where the web service is) in my web service code that I usually shove in my Model (I know some people think that is not the right place to put that code and that you should create a 'Service class' to handle web service calls).

But, with MEF, things happen "at a later point than normal", so I needed to add that bit of code behind. Since that code behind is not anything a Designer would be concerned with, I am not worried about messing up my ViewModel separation.

Yes there is. "SelectedMEFModule.Value" is an instance of the object in the .xap so I can cast "SelectedMEFModule.Value" to the class that it represents (or a class that it inherits from) and set a property or call a method on that object.

I will have a tutorial in a few weeks that demonstrates that, but for now you may find help faster in the MEF forum on http://Silverlight.net.

I like the fact that you focused on a very specific scenario for using MEF. When we designed DeploymentCatalog we definitely had the "let me just split my app up" idea in mind. Thanks for making it more digestable.