Wednesday, May 9, 2012

MEF : Beyond Export and Import

I am going to describe some of advanced features of MEF

1) Container.SatisfyImportOnce Or Container.ComposeParts methods satisfies import/export only when they are called, any further changes in catalogs doesn't impact old created object.
eg.
AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
container.SatisfyImportsOnce(this);
 
2) AllowRecomposition attribute is used to stop any changes in old composed objects if there is any changes in Container's catalog items.
eg.
[ImportMany(AllowRecomposition = false)]
public IEnumerable<ICustomType> Strings { getset; } 


3) PartCreationPolicyis used to specify whether to create a Singleton instance of required object or multiple instance based on request. You can RequiredCreattionPolicy attribute to specify PartCreationPolicy for a particular type.

eg. Following line will give error as it will fail to satisfy PartCreationPolicy.
[ExportPartCreationPolicy(CreationPolicy.NonShared)] public class CustomClass {..}
[Import(RequiredCreationPolicy = CreationPolicy.Shared)] CustomClass _inst1;


4) AllowDefault attribute can be used when you don't have any export to satisfy for a required import. If you dont set this attribute as true, you will get an exception if there is no export to satisfy an import.

5) InhertitedExport attribute can be used with a base class / interface to specify that all its child classes will export base-class or interface types.

eg. In following example Type1 and Type2 will export ICustomType as ICustomType is marked with InheritedExport attribute.

    [InheritedExport(typeof (ICustomType))]
    public interface ICustomType
    {
    }
 
    public class Type1 : ICustomType {}
    public class Type2 : ICustomType {}
 
6) You can implement IPartImportsSatisfiedNotification interface for your class, 
when you want to be notified about Imports satisfied event.
 
7) You can use ImportingConstructor attribute, if you are using parametrized constructors 
and have a constructor parameter which can which needs to be imported. 

No comments:

Post a Comment