DCSIMG
OS aware plug-ins - Bnaya Eshet

Bnaya Eshet

Disclaimer

OS aware plug-ins

you can download the sample here

This post assume that you familiar with MEF technologies, you can fined more resources here and here.

Background

I’m currently working at Sela Group on project that demonstrate the different capabilities appended to Windows 7.
This project architecture involve plug-ins (using MEF architecture) and we needed way to instantiate only those plug-ins that support the runtime operating system.

MEF Metadata

MEF support lazy instantiation and metadata which can be inspect before the instantiation.

Plug-ins decoration

MEF support decoration by using the Metadata attribute, also you can use that attribute out of the box, we decide to have strongly metadata technique.

In order to achieve our goal we follow the next steps:

1) First we have to define how our metadata contract:

public interface ISupportedOS {
    OSSupported OSSupported { get; }
}

2) Then we define our metadata attribute:

[MetadataAttribute ]
[AttributeUsage (AttributeTargets.Class)]
public class ExportWithMetaAttribute
      :ExportAttribute,ISupportedOS{
    public ExportWithMetaAttribute(Type exportType,
        OSSupported eSupportedOS )
        :base(exportType){
        this.OSSupported = eSupportedOS;
    }
    public OSSupported OSSupported { get; set; }
}

3) Now we have to decorate our Plug-in:

[ExportWithMetaAttribute (typeof (ICommand), 
OSSupported.Windows7)] [PartCreationPolicy (CreationPolicy.Shared)] public class Win7Command: ICommand {

Consuming the plug-ins

Getting the metadata is easy, all we have to do is to add our metadata contract (interface) after the imported type.

Property looks like:

[ImportMany]
public Lazy<ICommand,ISupportedOS> Commands{get;set;}

GetExports looks like:

var commands = container.GetExports<ICommand, ISupportedOS> ();

Loading OS aware plug-ins

The following code snippet show the final step which is to decide whether or not the plug-is compatible with out OS:

foreach (var command in commands) {
  if (command.Metadata.OSSupported.IsSupported())
    command.Value.Execute ();
}

Summary

MEF lazy instantiation and metadata capabilities give us great control on our plug-ins composition.

You can download the sample code and explore the concept.

Posted: Aug 21 2009, 06:57 PM by bnaya
תגים:,

Comments

No Comments