Exporting non Exportable types

2010/10/30

Exporting non Exportable types

MEF, Compose, Import, Export, Poco this post extend Glenn Block‘s post about

"Poco, Mef, and custom type systems. Are you ready to take the red pill?" 

the post is adding a compile time attribute export model, Directory catalog

and migrate Glenn code to VS 2010.

It is very recommended to read Glenn Block‘s post before reading

this one.

 

the code sample for this post can be download from here.

 

Summarizing Glenn’s post

in general Glenn show how to add attributes (like Export) to 3rd party type

which doesn’t support it (it is cool technique which doesn’t related directly to MEF).

Glenn show how to write catalog which can be aware of types extension.

 

What was added?

I took Glenn’s source, fix it to run against the CLR 4.0,

then I added a directory catalog which aware of the

type extension and I also add a nice clean way of exposing the type

by using assembly level attribute.

 

the directory catalog is very straight forward so I wont cover it in the post

(you can download the source and see the implementation).

 

the following code show how to use the assembly level attribute:

Code Snippet
  1. [assembly: ComposablePartRegistry(typeof(MyNoneExportedType), typeof(IMyNoneExportedType))]

as you can see, all you have to do is to declare the exported type followed by the exported contract.

 

the attribute snippet:

Code Snippet
  1. [AttributeUsage (AttributeTargets.Assembly)]
  2. public class ComposablePartRegistryAttribute : Attribute
  3. {
  4.     public ComposablePartRegistryAttribute(
  5.         Type implementation, Type contract,
  6.         CreationPolicy policy = CreationPolicy.Any)
  7.     {
  8.         Type t = typeof (ComposablePartType<,>);
  9.         t = t.MakeGenericType(new[] {implementation, contract});
  10.         Type = Activator.CreateInstance(t, policy) as TypeDelegator;
  11.     }
  12.  
  13.     public TypeDelegator Type { get; private set; }
  14. }

line 8-10: creating ComposablePartType type which later be used by the catalog.

 

Summary

this was small extension to Glenn’s concept which can be very useful

in cases where you want to embrace 3rs party component into your MEF model.

 

kick it on DotNetKicks.com Shout it

Digg This
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>