DOCX

Introduction to the Managed Extensibility Framework

By Katie Freeman,2014-09-18 17:47
9 views 0
Introduction to the Managed Extensibility Framework in VS2010;microsoft technology.

Hands-On Lab

    Introduction to the Managed Extensibility

    Framework

Lab version: 1.0.0

Last updated: 9/18/2011

CONTENTS

    OVERVIEW ............................................................................................................................................. 3

    EXERCISE 1: USING MEF TO EXTEND AN APPLICATION .................................................................. 5

    Task 1 Updating Your Application to Load Composable Parts ........................................................ 6

    Task 2 Updating Your Composable Part to Export Contracts ........................................................ 11

    Task 3 Creating a New Extension ................................................................................................. 16 Exercise 1: Verification 23

    EXERCISE 2: USING METADATA AND LAZY-LOADING MODULES.................................................. 23

    Task 1 Attaching Metadata to an Export ...................................................................................... 24

    Task 2 Using a Custom Export Attribute ...................................................................................... 25

    Task 3 Importing Metadata ......................................................................................................... 32

    Exercise 2: Verification 38

    EXERCISE 3: USING MEF AND SILVERLIGHT 4 ................................................................................ 40

    Task 1 Convert Extensions to Silverlight ...................................................................................... 40

    Task 2 Create Silverlight Cash Maker UI ....................................................................................... 48

    Task 3 Update Your Silverlight Application to Load Composable Parts ......................................... 55

    Task 4 Load Silverlight Extensions Dynamically ............................................................................ 57 Exercise 3: Verification 61

    SUMMARY ............................................................................................................................................ 64

Overview

    The Managed Extensibility Framework (MEF) allows developers to provide hooks into their .NET applications for extensions by first and third parties. MEF can be thought of as a general application extension facility.

    MEF enables developers to create extensions dynamically, without the extending application or the extension requiring any specific knowledge of the other. This ensures no coupling exists between the two at compile time, enabling applications to be extended at runtime, without the need to recompile. MEF also provides the ability to examine the metadata of an extension assembly before loading the extension into the application -- a much faster approach.

    Several key concepts relating to extensibility are covered in this lab:

    ; Composition is the practice of combining several objects with discrete functionality into one or

    more complex objects. Composition is not inheritance of functionality from a parent class, but is

    instead the assembling of several different objects into one. For example, Wing, Propeller,

    Fuselage, and VerticalStabilizer objects could be composed as part of an Aircraft object.

    ; ComposableParts are the key building blocks of MEF. ComposableParts enable applications to

    expose and consume component extensions via Exports and Imports.

    ; Contracts are the avenue for communication between Export and Import components. A

    Contract is normally implemented via an Interface class. Contracts enable MEF

    ComposableParts to avoid dependencies or tight coupling with other components.

    ; Conditional Binding allows loading of components, which meet specific metadata criteria.

    Following the example above, you might choose to load VerticalStabilizer components, which

    were made only of composite graphite.

    Extensibility is achieved, primarily, by adding Import attributes at appropriate points in the application

    and adding corresponding Export attributes to the extensions. Import and Export attributes can be

    thought of in the same aspect as a supplier and consumer respectively. Export components supply some

    value; Import components consume that value. Other options for extensibility are open to developers, including completely custom extensibility approaches; however, this lab focuses solely on the primary approach discussed above. Moreover, the components can be imported using the ImportMany attribute,

    which loads all the components that match the given contract as a collection.

    With the release of Silverlight 4, MEF has been included in it, allowing you to extend rich internet applications. This does not imply that MEF can only be used with Silverlight 4; using the version available in codeplex (http://mef.codeplex.com), MEF can be used to compose applications created in Silverlight 3.

Objectives

    In this Hands-On Lab, you will learn how to:

    ; Create extensibility modules and components

    ; Import Extended assemblies while an application is running

    ; Extend a Silverlight 4 application (optional)

System Requirements

    You must have the following items to complete this lab:

    ; Microsoft Visual Studio 2010

    ; .Net Framework 4

    ; Silverlight 4 (optional)

    ; Silverlight 4 SDK (optional)

    ; Silverlight 4 Tools for Visual Studio 2010 (optional)

Setup

    All the requisites for this lab are verified using the Configuration Wizard. To make sure that everything is correctly configured, follow these steps.

    Note: To perform the setup steps you need to run the scripts in a command window with administrator privileges.

    1. Run the Configuration Wizard for the Lab if you have not done it previously. To do this, run the

    CheckDependencies.cmd script located under the Source\Setup folder of this lab. Install any

    pre-requisites that are missing (rescanning if necessary) and complete the wizard.

    Note: For convenience, much of the code you will be managing along this lab is available as

    Visual Studio code snippets. The CheckDependencies.cmd file launches the Visual Studio

    installer file that installs the code snippets.

Exercises

    This Hands-On Lab comprises the following exercises:

    1. Using MEF to Dynamically Add Modules to an Application

    2. Using Metadata and Lazy-Loading Modules

    3. Using MEF and Silverlight 4

Starting Materials

    This Hands-On Lab includes the following starting materials.

    ; Visual Studio solutions. Depending on the exercise you will find Visual Studio solutions that you

    can use as starting point for the exercises.

    Note: Each exercise is accompanied by an End folder containing the resulting solution you should

    obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises.

Note: Each exercise contains a Visual Basic and a C# version; Inside the End/Begin solution folder, you

    will find two folders: VB, containing the Visual Basic version of the exercise, and C#, containing the C#

    version of it.

Estimated time to complete this lab: 30 minutes.

Next Step

    Exercise 1: Using MEF to Dynamically Add Modules to an Application

    Exercise 1: Using MEF to Extend an Application

    One practical use of the Managed Extensibility Framework is adding modules to an application at runtime. This is useful in a scenario in which users chooses specific modules to purchase or install originally and may add more modules at a later time. Using MEF, you can configure your application to monitor a well-known directory and add any module assemblies found in that directory. Dropping module assemblies into a directory allows your application to load those assemblies without explicitly setting references to them.

Task 1 Updating Your Application to Load Composable Parts

    In this task, you will modify an existing WPF Window class to create extension hooks that will allow

    dynamically importing queries. You will update this query classes later in this exercise.

    1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 |

    Microsoft Visual Studio 2010.

    2. Open the ContosoAutomotive.sln solution file. By default, this file is located in the folder

    Source\Ex1\begin (choosing the folder that matches the language of your preference.)

    3. Add a reference to the MEF library on the ContosoAutomotive project. To do this:

    a. Select the ContosoAutomotive project in the Solution Explorer and select Project | Add

    Reference… The Add References dialog appears.

    b. Select the .NET tab and then select the System.ComponentModel.Composition

    component. Click the OK button to add a reference to this library.

    Figure 1

    Add a Reference to the MEF library.

    4. Open the App class in code view. To do this, right-click on the App.xaml file in the Solution

    Explorer and select View Code.

    5. Update the App class to use the MEF library. To do this, add the following statement on top of the using clause list above the App class definition.

    C#

    using System.ComponentModel.Composition.Hosting;

Visual Basic

    Imports System.ComponentModel.Composition.Hosting

    6. Create an aggregate catalog to load parts from the current application assembly and from assemblies located in the current folder in the file system. Also, create a composition container instance based on it and create an exported CashMaker instance. To do this, modify the AppStartup method with the following code.

    (Code Snippet Intro to MEF Lab - Ex1 Task1 Step6 - StartupCatalogAndContainer CSharp) C#

    void AppStartup(object sender, StartupEventArgs args)

    {

     var catalog = new AggregateCatalog(new DirectoryCatalog("."),

     new AssemblyCatalog(Assembly.GetExecutingAssembly()));

     var container = new CompositionContainer(catalog);

     var window = container.GetExportedValue<CashMaker>();

     window.Show();

    }

    (Code Snippet Intro to MEF Lab - Ex1 Task1 Step6 - StartupCatalogAndContainer VB) Visual Basic

    Sub AppStartup(ByVal sender As Object, ByVal args As StartupEventArgs)

    {

     Dim catalog = New AggregateCatalog(New DirectoryCatalog("."),

     New AssemblyCatalog(Assembly.GetExecutingAssembly()))

     Dim container = New CompositionContainer(catalog)

     Dim window = container.GetExportedValue(Of CashMaker)()

     window.Show()

    }

    Note: The starting point for enabling MEF composability is creating a composition container based on one or several catalogs. MEF's container interacts with Catalogs to have access to

    composable parts. The container itself resolves a part's dependencies and exposes Exports to

    the outside world. In addition, you are free to add composable part instances directly to the container if you wish.

    Note: There are different kinds of Catalogs, which are able to discover parts on different ways. This exercise uses an Aggregate Catalog combining a Directory Catalog searching on the Application directory (represented by the “.”) and Assembly Catalog for look at the types inside

    the application assembly (retrieved using the Assembly.GetExecutingAssembly method).

    The full list of Catalogs available on MEF is:

    - Assembly Catalog: Discovers the different parts on a specific assembly.

    - Directory Catalog: Discovers parts inside the assemblies on a specific directory.

    - Aggregate Catalog: Allows use more than one catalog combining them.

    - Type Catalog: Looks inside the assemblies for specific types.

    For more information on Catalogs, see Using catalogs.

    Note: Application’s main window is also located and loaded using MEF through the container’s GetExportedValue method. In the following steps, you will decorate the CashMaker class

    (which is the main window) with the Export attribute to be discoverable by MEF.

    The GetExportedValue method will throw an exception if no parts or more than one

    implement the solicited contract. This is not a problem in the exercise implementation because we are not using an interface to discover the type, we are using the class itself so it have to be defined and cannot be duplicated ensuring that MEF will find only one instance.

    7. Open the CashMaker Window in code view. To do this, right-click on the CashMaker.xaml file in

    the Solution explorer and select View Code.

    8. Update the CashMaker class to use the MEF library. To do this, add the following statement at the top of the CashMaker class definition.

    C#

    using System.ComponentModel.Composition;

Visual Basic

    Imports System.ComponentModel.Composition

    9. Since the CashMaker class is now a composable part you will export the class making it available

    to the composition container. To do this, decorate the CashMaker class with the Export

    attribute as shown in the code below.

    C#

    [Export]

    public partial class CashMaker : Window

    {

    ...

    }

Visual Basic

    <Export()>

    Class CashMaker

     Inherits Window

    ...

    End Class

    NOTE: Import and Export values are interconnected with unique Contracts. Contracts serve as uni-directional bridges. An export contract can consist of further metadata used to filter on its

    discovery. For example, it might indicate a specific capability that the export offers.

    As you decorate the CashMaker class with the Export attribute, it will discover composable parts exporting the ICarQuery contract, defined in the ContosoAutomotive.Common project.

    You will declare a collection to hold the Imports and expose them through a property. MEF's composition container will resolve applicable Exports and Imports loading the collection for you.

    10. Add the following code to the CashMaker.xaml.cs (C#) or CashMaker.xaml.vb (Visual Basic) file,

    just above its constructor.

    (Code Snippet Intro to MEF Lab - Ex1 Task1 Step10 - ImportedCarQueries CSharp) C#

    [ImportMany(AllowRecomposition = true)]

    public ObservableCollection<ICarQuery> CarQueries { get; set; }

    (Code Snippet Intro to MEF Lab - Ex1 Task1 Step10 - ImportedCarQueries VB) Visual Basic

    <ImportMany(AllowRecomposition:=True)>

    Public Property CarQueries() As ObservableCollection(Of ICarQuery)

Note: You can import collections with the ImportMany attribute. This means that all instances

    of the specific contract will be imported from the container.

    MEF parts can also support recomposition. This means that as new exports become available in the container, collections are automatically updated with the new set.

    11. Once MEF completes the CarQueries collection import process, you want your application to be notified and so it can take a particular action. To do this, make the CashMaker class to implement the IPartImportsSatisfiedNotification interface as shown in the following code. C#

    [Export]

    public partial class CashMaker : Window, IPartImportsSatisfiedNotification

    {

    ...

    }

Visual Basic

    <Export>

    Public Partial Class CashMaker

     Inherits Window

     Implements IPartImportsSatisfiedNotification

    ...

    End Class

    12. Implement the IPartImportsSatisfiedNotification interface and bind the CarQueries collection to the UI by setting the DataContext property of the commandGrid control. To do this, paste the following OnImportsSatisfied method code inside the CashMaker class.

    (Code Snippet Intro to MEF Lab - Ex1 Task1 Step12 - OnImportsSatisfied CSharp) C#

    public void OnImportsSatisfied()

    {

     this.commandGrid.DataContext = this.CarQueries;

    }

(Code Snippet Intro to MEF Lab - Ex1 Task1 Step 12 - OnImportsSatisfied VB)

    Visual Basic

    Public Sub OnImportsSatisfied() Implements IPartImportsSatisfiedNotification.

    OnImportsSatisfied

     Me.commandGrid.DataContext = Me.CarQueries

Report this document

For any questions or suggestions please email
cust-service@docsford.com