Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C# 4.0

First Guide to MEF and Silverlight (Part II)

Rate me:
Please Sign up or sign in to vote.
4.93/5 (28 votes)
26 Aug 2010CPOL8 min read 59K   426   36   20
In this article, I describe MEF using a Silverlight Application. Read it and don't forget to vote and share your feedback.

Introduction

In my previous article, “First Guide to MEF & Silverlight (Part–I)”, I discussed about MEF with a small simple console application. Hope that was useful to you to understand the basics of MEF. In this article, I will guide you to create a simple Silverlight application using the MEF. If you are new to MEF, I strongly recommend you read my previous article to gain knowledge on the basic things of MEF like Importing, Exporting, Catalog, Container, etc. Read the complete article and at the end if you have any queries, please let me know. I will try to answer them as soon as possible. I always appreciate your valuable feedback.

Prerequisite

To start working with the Silverlight & MEF application, you need to setup your development environment. In your development PC, you need the following things already installed:

  1. Visual Studio 2010 with .NET Framework 4.0
  2. Silverlight 4.0 Tools for Visual Studio 2010

Once your environment is ready with the above tools, we can start with our next step.

Setting up the Project

First of all, we need to create a Silverlight application project and then we have to add some assembly reference in order to work with the MEF. Hence, follow the steps given below to setup your project:

  • Open your Visual Studio 2010 IDE
  • Now go to File –> New –> Project or just press Ctrl + Shift + N to open the “New Project” dialog window.
  • From the left panel, expand “Visual C#” and then select “Silverlight”. This will populate the right pane with the Silverlight templates.

    Image [http://www.kunal-chowdhury.com]

  • In the right pane, select “.NET Framework 4” from the DropDown present at the top of the screen. This is required because we want to do application programming for the target version, i.e. Framework 4.
  • Chose “Silverlight Application” from the right pane and click “OK”. I assumed that you selected the proper location and named your application project properly (in our case, I named it as “MEFWithSilverlightDemo”).
  • Once you click “OK”, it will ask you to create a new Web site. This step is required to host the Silverlight application.

    Image [http://www.kunal-chowdhury.com]

  • Be sure that, in the above dialog, “Silverlight 4” has been selected as the Silverlight version.
  • Once you click “OK”, the Visual Studio IDE will start creating your Silverlight project. It will create two projects (one is your Silverlight application project and the other is your Silverlight application hosting website).

    Image [http://www.kunal-chowdhury.com]

  • Once the project has been created by the IDE, you need to add a reference of the Assembly named “System.ComponentModel.Composition” and a reference of the Assembly named “System.ComponentModel.Composition.Initialization” to your project. To do this, right click on your Silverlight Application project and click “Add Reference”. From the “Add Reference” dialog, find the assembly named “System.ComponentModel.Composition” and “System.ComponentModel.Composition.Initialization” to add them to your project.

    Image [http://www.kunal-chowdhury.com]

Once done with all the above steps, your project is ready for the MEF development.

Building our First MEFWithSilverlightDemo Application

Let us first decide what we want to do in our example. We will create a Silverlight application where we will include some UserControls as a Widget. This is for learning purposes and hence don’t go with the UI. So, in our sample application, we will create a UserControl and mark it as Exportable. Then we will import the UserControl in our application to add it in the UI. Next, we will create another UserControl and mark it as Exportable, so that without any other change in the code, it should add in the main UI. This is just an example to showcase the MEF functionality in Silverlight applications.

Common Interface Design

Let’s jump into the code. First of all, we will create an Interface called IWidget and we will use this interface to build our UserControl. We will just inherit this to the UserControl and while exporting or importing, we will use the same interface type. The reason behind this is to make sure only the specified type of control will be marked for MEF. If we have two different types for two different kind of controls, it will be easier for us to manage in the main screen. So, just create a blank interface named IWidget which will look like below:

Hosting the Controls

Now, in the MainPage.xaml, add an ItemsControl & name it as “widgets”. Wrap the ItemsControl with a StackPanel to hold the items. The XAML file will look as below:

Designing Employee Widget

Now it’s time to create a UserControl. Right click on the Silverlight project and add one UserControl & name it as “EmployeeWidget”. We will not design more inside it as it is not required to understand the MEF. To make it properly visible, just add one TextBlock with some strings. In our example, I am setting “Employee Widget” as the text string for the TextBlock and also setting a color “Red” to the Grid background. Resize the UserControl to 150 x 150, so that it will set properly in the screen. Let’s see the below code for a detailed layout:

As mentioned above, I resized the control to 150 x 150 and then changed the background color to Red. Added a TextBlock having “Employee Widget” as the value to the TextProperty of the TextBlock with a foreground color of White so that it will be visible on top of the Red color. No need to describe more on it. Just check the above XAML and you will get the idea behind it.

Exporting Employee Widget

Press F7 in the EmployeeWidget.xaml page to open up the code behind file. Inherit the EmployeeWidget class from IWidget. Once done, add the attribute “Export” having the type of IWidget to the class. This will ensure that the class will export for the MEF to satisfy. Look into the code here:

Importing the Widget

As our UserControl has been exported for the MEF to satisfy, it’s time to import it in our MainPage. To do this, open the MainPage.xaml.cs and create a property “Widgets” of IWidget type array. We are using array type to ensure that we can import many widgets there. So, mark the property with the attribute “ImportMany” of type IWidget. Once that is done, our code is ready to import the exported class. Now inside your MainPage constructor, iterate through the array and add all the Widgets as the items to the “widgets” items control which we already added in the XAML. Now if you run your application, you will notice that the Widgets array is null. Why? Just think. Oh yea!!! We forgot to satisfy the MEF Initializer to satisfy the property. What so we do for that? To satisfy the imports, you need to call “CompositionInitializer.SatisfyImports(this);” just before iterating through the array list. Have a look into the code:

Now, run your application once again and this time you will see the EmployeeWidget added to the UI screen with a text “Employee Widget” having a Red background. Here is the screenshot of the same:

image

Woho!!! Nice. We didn’t create the object of the UserControl and add it to the ItemsControl. The MEF framework did it for us. Once satisfied, it created the object and imported it to the MainPage.

Designing Customer Widget

That’s it. Now we will do one more thing. We will create another UserControl named “CustomerWidget” and follow the same steps mentioned above for exporting the control. This time, we will set the text to “Customer Widget” and will set the background color to Green. This will make it easy for us to distinguish between the items. Here is the XAML code of the CustomerWidget usercontrol:

Exporting Customer Widget

Now open the code behind file of CustomerWidget by pressing F7 in the XAML page and follow the same step as we did for the EmployeeWidget, i.e. implement the CustomerWidget from the interface named IWidget and mark the class exportable by setting the Export attribute of the IWidget. Here is the code for your reference:

That’s it. This time we didn’t add/modify anymore code in our MainPage. Just run the application and you will see the CustomerWidget added in the panel along with the control named EmployeeWidget. See the screenshot of the same here:

image

Summary

So, what did we learn here? We learnt that without changing the original code, we can easily import any control with the help of MEF. It is very easy to plug something into our original application without making any change in the main application. In such a case, instead of updating the original application, we can easily attach our feature like a plug-in. Hope, this article helped you to understand the basic functionality of MEF with the help of Silverlight. In my next article, I will show you more on MEF with the help of a Console Application. Till then, keep learning about MEF & do your small POCs to learn in depth. Please don’t forget to post your feedbacks and/or suggestions to improve this article. I appreciate your time for reading through this article.

History

  • 24th August 2010 - Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India

Kunal Chowdhury is a former Microsoft "Windows Platform Development" MVP (Most Valuable Professional, 2010 - 2018), a Codeproject Mentor, Speaker in various Microsoft events, Author, passionate Blogger and a Senior Technical Lead by profession.

He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows app development. He posts his findings, articles, tutorials in his technical blog (www.kunal-chowdhury.com) and CodeProject.


Books authored:


Connect with Kunal on:





Comments and Discussions

 
GeneralMy vote of 4 Pin
Mico Perez14-Aug-11 21:48
Mico Perez14-Aug-11 21:48 
GeneralMy vote of 4 Pin
bluetiger092026-Apr-11 23:42
bluetiger092026-Apr-11 23:42 
QuestionHow to tell CompositionInitializer to get a new instance Pin
njs200222-Dec-10 8:55
njs200222-Dec-10 8:55 
GeneralWould you past actual code text instead of images Pin
Sung M Kim29-Aug-10 3:31
professionalSung M Kim29-Aug-10 3:31 
AnswerRe: Would you past actual code text instead of images Pin
Kunal Chowdhury «IN»29-Aug-10 3:37
professionalKunal Chowdhury «IN»29-Aug-10 3:37 
GeneralRe: Would you past actual code text instead of images Pin
Sung M Kim29-Aug-10 4:12
professionalSung M Kim29-Aug-10 4:12 
Hi, Kunal.

Thank you for the quick reply.
"Browsing Code" tab made me lose the track of where I was reading.

For some reason, when I ran your source code, I was prompted to install Silverlight on IE, FF & Chrome.
But after downloading the installer, i was getting a message saying that my Silverlight is already up-to-date.

It was a weird issue but I ended up writing from scratch and it worked like charm.

Now moving on to the part III...
May you live the rest of your day...

AnswerRe: Would you past actual code text instead of images Pin
Kunal Chowdhury «IN»29-Aug-10 4:16
professionalKunal Chowdhury «IN»29-Aug-10 4:16 
GeneralMy vote of 5 Pin
defwebserver25-Aug-10 2:11
defwebserver25-Aug-10 2:11 
GeneralRe: My vote of 5 Pin
Kunal Chowdhury «IN»25-Aug-10 5:18
professionalKunal Chowdhury «IN»25-Aug-10 5:18 
GeneralNice...have a Pin
Sacha Barber25-Aug-10 1:12
Sacha Barber25-Aug-10 1:12 
GeneralRe: Nice...have a Pin
Kunal Chowdhury «IN»25-Aug-10 1:23
professionalKunal Chowdhury «IN»25-Aug-10 1:23 
GeneralRe: Nice...have a Pin
Kunal Chowdhury «IN»27-Aug-10 10:29
professionalKunal Chowdhury «IN»27-Aug-10 10:29 
GeneralRe: Nice...have a Pin
Sacha Barber27-Aug-10 21:46
Sacha Barber27-Aug-10 21:46 
GeneralMy vote of 5 Pin
venugopalm25-Aug-10 0:11
venugopalm25-Aug-10 0:11 
GeneralRe: My vote of 5 Pin
Kunal Chowdhury «IN»25-Aug-10 1:22
professionalKunal Chowdhury «IN»25-Aug-10 1:22 
GeneralMy vote of 5 Pin
Abhijit Jana24-Aug-10 16:05
professionalAbhijit Jana24-Aug-10 16:05 
GeneralRe: My vote of 5 Pin
Kunal Chowdhury «IN»24-Aug-10 19:36
professionalKunal Chowdhury «IN»24-Aug-10 19:36 
GeneralMy vote of 5 Pin
Pete O'Hanlon24-Aug-10 9:25
mvePete O'Hanlon24-Aug-10 9:25 
GeneralRe: My vote of 5 Pin
Kunal Chowdhury «IN»24-Aug-10 14:37
professionalKunal Chowdhury «IN»24-Aug-10 14:37 
NewsRe: My vote of 5 Pin
Kunal Chowdhury «IN»27-Aug-10 10:27
professionalKunal Chowdhury «IN»27-Aug-10 10:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.