January 2013 - Posts
MEF 2.0 - mini series: Part 7 (Catalog filter and Deep hierarchic scoping)
this is the 7th post in the MEF 2.0 mini series.
you can see the following TOC for other posts in this series.
in the previous post I was talking about composition scoping and lifetime management.
on this one, I will extend the composition scoping topic toward hierarchic along with catalog filtering capability.

hierarchic scoping is not trivial, you must understand the hierarchic behavior and what it was design for.
MEF hierarchic was design to enable parts from higher scope to access lower scope's part without re-instantiation, lower part do not target higher scope's part directly.
each hierarchic scope construct by importing a ExportFactory<T> (which we saw in the previous post).
I will try to make it as simple as I can.
the following diagram demonstrate the idea of sub scope that interact with its parent scope's items.

let try to have a similar code structures.
I will use a plug-in base class to trace the instantiations:
Code Snippet
- public abstract class PluginBase
- {
- private static int _globalId = 0;
- protected int _id;
-
- public PluginBase()
- {
- _id = _globalId++; // not thread-safe
- }
- }
derived class's ids will be incremented per instantiation.
the following snippet include the classes which will be used for our hierarchic demonstration:
Code Snippet
- public class Level1ScopeRoot : PluginBase
- {
- [Import]
- public Level1ItemA ItemA { get; private set; }
- [Import]
- public Level1ItemB ItemB { get; private set; }
- }
-
- public class Level1ItemShared : PluginBase { }
-
- public class Level1ItemA : PluginBase
- {
- [Import]
- public Level1ItemShared ItemZ { get; private set; }
- }
-
- public class Level1ItemB : PluginBase
- {
- [Import]
- public Level1ItemShared SharedItem { get; private set; }
-
- [Import]
- public ExportFactory<Level2SubScopeRoot> SubScope { get; private set; }
- }
-
- public class Level2SubScopeRoot : PluginBase
- {
- [Import]
- public Level2SubItem1 SubItem1 { get; private set; }
-
- [Import]
- public Level2SubItem2 SubItem2 { get; private set; }
- }
-
- public class Level2SubItem1 : PluginBase
- {
- [Import]
- public Level1ItemShared ItemShared { get; private set; }
- [Import]
- public Level2SubItemShared SubItemShared { get; private set; }
- }
-
- public class Level2SubItem2 : PluginBase
- {
- [Import]
- public Level2SubItemShared SubItem { get; private set; }
- }
-
- public class Level2SubItemShared : PluginBase { }
all the classes prefixed with the scoping 'Level'.
referring a sub-scope required using of ExportFactory<T> (line 23).
the following diagram is showing their hierarchic and dependencies graph:

our final step is to define a catalog per scope's hierarchic and to set hierarchic structure.
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForTypesDerivedFrom<PluginBase>()
- // add ScopeLevel metadata
- .AddMetadata("ScopeLevel", t => t.Name.StartsWith("Level1") ? 1 : 2)
- .Export<PluginBase>();
-
- var catalog = new AssemblyCatalog(typeof(Program).Assembly, picker);
-
- var catalogL0 = catalog.Filter(p => p.ContainsPartMetadata("ScopeLevel", 1));
- var catalogL1 = catalog.Filter(p => p.ContainsPartMetadata("ScopeLevel", 2));
-
- var scopeL1 = new CompositionScopeDefinition(catalogL1, null);
- var scopeL0 = new CompositionScopeDefinition(catalogL0, new[] { scopeL1 });
-
- var container = new CompositionContainer(scopeL0);
at line 2-5, I export everything inherits from 'PluginBase' and adding a 'ScopeLevel' metadata with the right scope leveling value.
line 7, define a general assembly catalog (which will be the base for the filtered catalogs).
lines 9,10, are defining a filtered catalog for each scoping level (filtering an existing assembly catalog).
lines 12,13, defines the hierarchic between the scoped catalogs.
line 15, create a container with the top level scope.
now we're ready for a composition.
here you can download a sample code.
Summary
I consider this feature as MEF 2's most complex one.
Hierarchic can become complex, so use it with caution.
This Week On Channel 9
my blog was manage to get on Channel 9 week's top developer news.

MEF 2.0 - mini series: part 6
(Composition scoping and lifetime management)
this is the 6th post in the MEF 2.0 mini series.
you can see the following TOC for other posts in this series.
in this post I will cover a new concept of scoping and part lifetime management, which is a great improvement over MEF 1.

MEF 1 was coming with a fairly naïve lifetime management.
part's lifetime could be either shared or non-shared (you could also apply 'any' but eventually 'any' will be created as shared or non-shared).
shared is a singleton instantiation, while non-shared will create a new instance each time.
MEF 1's instantiation model doesn't support a complex scenario where some dependency's lifetime should be dictate by the lifetime of other unites.
you can conceder a UI window that is having plug-ins that should be dispose while the UI window is closing.
for example consider you have the following components (parts) dependency flow:

the application can have multiple processes.
each process is having some plugins, but each view should have different instantiation of the plugins.
until now you can argue that a non-shared instantiation will do the job.
the next dependency level (DAL) should be shared under the boundary of a process but shouldn't be shared across processes.
this one can neither handle by the share nor by non-shared instantiation.
single instance of DAL should be created under each view scope.
MEF 2 added a scoped lifetime management.
I will use the attribute based model for this sample, but it will work in the same way in the fluent model.
Code Snippet
- [Export]
- public class Application
- {
- [Import]
- private ExportFactory<ProcessA> ProcAFactory { get; set;}
- [Import]
- private ExportFactory<ProcessB> ProcBFactory { get; set;}
- }
-
- [Export]
- public class ProcessA
- {
- [Import]
- public PluginA PlugA { get; private set; }
- [Import]
- public PluginB PlugB { get; private set; }
- }
-
- [Export]
- public class ProcessB
- {
- [Import]
- public PluginA PlugA { get; private set; }
- [Import]
- public PluginB PlugB { get; private set; }
- }
-
- [Export]
- public class PluginA
- {
- [Import]
- public DAL Dal { get; private set; }
- }
-
- [Export]
- public class PluginB
- {
- [Import]
- public DAL Dal { get; private set; }
- }
-
- [Export]
- public class DAL
- {
- }
at line 4-7 you can see a new type of importing target called ExportFactory<T> this type will initialize the scope.
It is having a CreateExport method that return a ExportLifetimeContext<T> can control the part life time.
the full implementation of the Application class is:
Code Snippet
- [Export]
- public class Application
- {
- [Import]
- private ExportFactory<ProcessA> ProcAFactory { get; set;}
- [Import]
- private ExportFactory<ProcessB> ProcBFactory { get; set;}
-
- public void WriteLayoutA()
- {
- using (ExportLifetimeContext<ProcessA> lifeOfA = ProcAFactory.CreateExport())
- {
- ProcessA a = lifeOfA.Value;
- Console.WriteLine("Proc A");
- Console.WriteLine("\tPlug A: {0}", a.PlugA.GetHashCode());
- Console.WriteLine("\t\tDal: {0}", a.PlugA.Dal.GetHashCode());
- Console.WriteLine("\tPlug B: {0}", a.PlugB.GetHashCode());
- Console.WriteLine("\t\tDal: {0}", a.PlugB.Dal.GetHashCode());
- }
- }
-
- public void WriteLayoutB()
- {
- using (ExportLifetimeContext<ProcessB> lifeOfB = ProcBFactory.CreateExport())
- {
- ProcessBb = lifeOfB.Value;
- Console.WriteLine("Proc B");
- Console.WriteLine("\tPlug A: {0}", b.PlugA.GetHashCode());
- Console.WriteLine("\t\tDal: {0}", b.PlugA.Dal.GetHashCode());
- Console.WriteLine("\tPlug B: {0}", b.PlugB.GetHashCode());
- Console.WriteLine("\t\tDal: {0}", b.PlugB.Dal.GetHashCode());
- }
- }
- }
you can see the usage of ExportFactory<T> at lines 11 and 24.
having a lifetime handled part is the first step for the scoping.
now we can define which part will be managed by the scope.
for each scope we except to find a single instantiation of each scoped part.
as you can see in the diagram below, the Plugins and the DAL should be instantiate once for each scope.

in order to define what's goes within the scope we should use the CompositionScopeDefinition as shown in the following code snippet:
Code Snippet
- static void Main(string[] args)
- {
- var scopeDependentCatalog = new TypeCatalog(
- typeof(ProcessA),
- typeof(ProcessB),
- typeof(PluginA),
- typeof(PluginB),
- typeof(DAL));
- var scopeDefDependent = new CompositionScopeDefinition(scopeDependentCatalog, null);
-
- var appCatalog = new TypeCatalog(typeof(Application));
- var scopeDefRoot = new CompositionScopeDefinition(appCatalog, new[] { scopeDefDependent });
-
-
- var container = new CompositionContainer(scopeDefRoot);
-
- var app = container.GetExportedValue<Application>();
-
- app.WriteLayoutA();
- Console.WriteLine("------------------------------------");
- app.WriteLayoutB();
- }
you can see the scope dependent definition at line 9
and the hierarchic between the scope and the application at line 12.
as you may notice it is possible to have deeper hierarchic, but this will be shown in future posts.
the output is:

remember that we was printing the part's hash code.
you can easily see that each process is having different plugin and DAL's instantiations, but even those the DAL was consumed by both plugins it has a single instantiation per scope.
Summary
scoping is a very powerful instantiation model which can solve some of the real-life scenario which wasn't fall into the shared or non-shared models.
in future post I will present a deeper hierarchic and the catalog filtering capability.
MEF 2.0 - mini series: part 5 (Fluent export properties)
this is the 5th post in the MEF 2.0 mini series.
you can see the following TOC for other posts in this series.
in this post I will cover the fluent property's export.

Exporting properties is a less known feature of MEF.
MEF 1 was supporting this feature by using the attribute model.
you could decorate a property with a [Export] attribute and then it become available for imports.
the following code demonstrate property exporting in MEF 1:
the Foo class is importing multiple SymmetricAlgorithm:
Code Snippet
- [Export]
- public class Foo
- {
- [ImportMany]
- public SymmetricAlgorithm[] CryptoProviders { get; private set; }
- }
and the CryptoComposer class is exporting a few symmetric algorithms:
Code Snippet
- [Export]
- public class CryptoComposer
- {
- [Export]
- public SymmetricAlgorithm Aes { get { return new AesManaged(); } }
- [Export]
- public SymmetricAlgorithm TripleDES { get { return new TripleDESCryptoServiceProvider(); } }
- [Export]
- public SymmetricAlgorithm RC2 { get { return new RC2CryptoServiceProvider(); } }
- }
with the following composition the Foo instance will have the CryptoComposer's symmetric algorithms:
Code Snippet
- var catalog = new AssemblyCatalog(typeof(Program).Assembly);
- var container = new CompositionContainer(catalog);
-
- var foo = container.GetExportedValue<Foo>();
so, how do we do it with the fluent export API?
to keep it simple I will leave the Foo class with the attribute model (we learned how to use fluent import in the previous post):
Code Snippet
- [Export]
- public class Foo
- {
- [ImportMany]
- public SymmetricAlgorithm[] CryptoProviders { get; private set; }
- }
-
- public class CryptoComposer
- {
- public SymmetricAlgorithm Aes { get { return new AesManaged(); } }
- public SymmetricAlgorithm TripleDES { get { return new TripleDESCryptoServiceProvider(); } }
- public SymmetricAlgorithm RC2 { get { return new RC2CryptoServiceProvider(); } }
- }
in order to export the CryptoComposer's properties you should use the following code:
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForType<CryptoComposer>()
- .ExportProperties(p => p.PropertyType == typeof(SymmetricAlgorithm));
-
- var catalog = new AssemblyCatalog(typeof(Program).Assembly, picker);
- var container = new CompositionContainer(catalog);
-
- var foo = container.GetExportedValue<Foo>();
summary
exporting properties using the fluent API is fairly straightforward.
Open House at Microsoft
yesterday I was lecturing at Microsoft about VS 2012, .NET 4.5, async/await, Rx and TPL Dataflow.
there was 90 people attended and I hope that everybody has learn something new.
the code sample for this lecture available here.

Async and AggregateException
this post is a complementary to Eran Stiller's post.
I was reading Eran Stiller's post about exception handling using async methods and I want to add a few side notes.

1) the exception handling behavior decisions is well documented in this post (by the TPL team), it decided after they had consider different options.
2) I was suggesting that compiler will check whether the a catch of AggregateException is implemented and if so to avoid the unwrapping behavior.
in this case the it can be assumed that programmer do expect multiple exceptions.
unfortunately, for the current version, I was speaking with them after the release of .NET 4.5.
I hope that we will see this mitigation in future release.
3) for the current version you can use the following work around if you do want to catch aggregate exception:
Code Snippet
- await Task.WhenAll(t1, t2)
- .ContinueWith(t => { if (t.Exception != null) throw t.Exception; });
by re-throwing the exception the unwrapped exception will be AggregateException.
it may be wise to wrap this pattern in an extension method because it can be a very repetitive one.
Proper Disclosure
Eran is one of my colleague and definitely one of the more talent Architect I was happened to work with.
Entity Framework - Pro and Con
Consulting as part of a consultant group can lead to better consulting.
Sela Israel consultant group is around 40 consultants many of them are speakers in local and international conference.
It happens that one of our customers was having some issues around the usage of Entity Framework.
even those I was thinking that I'm having most of the answer for that customer I decided to use our internal channel to query what are my colleagues opinions about those issues and sea whether they can enlighten a broader spectrum.
finally we end up with a very broad comprehended which we believe can be beneficial for a broader audience. it was Sasha advice that we should put a summary of our internal conversation into a blog post.
I will start with a few words about our customer's business.
the customer is using Entity Framework in a distributed environments.
his question was divided into a general ones and more focus, I will introduce each question and a summary of different answers provided by my colleagues and me.
I may say that many answers can be also true for other ORM frameworks like NHibernate.

the questions:
High-Level:
What are the best justifications for changing an existing system to work with entity framework?
- All-in-1 framework for mapping tables to classes, no need to write mapping code which is hard to maintain.
- Maintainability, easy to understand code, no need for plumbing or creating big data access layers.
- Provides LINQ queries over databases, which requires less understanding of SQL from junior developers.
- EF can be used as the base for data services and OData.
What are the scenarios you would defiantly NOT recommend to use entity framework?
- real-time apps.
- Code can only access the database through stored procedures. EF advantage is LINQ and change tracking which is not used when working solely with SPs (even those EF does have limited support for SP).
- Frequently insert operations (inserts). Bulk is not supported yet by EF.
- Frequently update operation, mainly when the update is targeting multiple rows (with a single value)
for example: UPDATE TableName SET ColumA = 10 WHERE ColumnB = ?
this kind of update does better be used with ExecuteNonQuery (either from the context or directly from Ado.Net). - De-normalized tables and high performance queries. EF generates queries and they are hard to manipulate, and it doesn't map well to de-normalized tables.
We want to work in a method of loading ALL data into memory is that recommended using Entity framework? What problems should we expect?
- Loading all entities will require many queries and a lot of time.
- Memory overhead.
- Latencies because of the EF change tracking and large collection handling.
- EF contexts are not thread-safe, you should not use one context for the entire service.
- If you do intend to do that, use EF for loading entities, but not for managing them (detach the entities from the content).
- do not use the context as a cache object (for distributed scenarios)
it is not thread safe, having overheads and doesn't follow the idea of separation of concern. it is much better to use a designated cache API like AppFabric Cache.
Technical-Level:
Memory leaks:
We have a scenario where every 10 seconds we open a context to get a single table and close it. "using (entities context = new entities(_connection)) {… }"
this caused a memory leak over a period of a few hours.
- I suggest you check the origin of the memory leaks to make sure it's from EF. EF is an open source now, so any memory leak can be reported and fixed.
- Use the Profiler and VMMap in order of tracing the leak's root.
Should we keep the context open in this case?
- It doesn't really matter, as the query will execute either way. However, it's preferable to close contexts so the cached entities will be GC'd, otherwise the context and the cached entities will be upgraded to Gen2 and will get stuck there for the duration of the service.
- NO! Use context per request for WCF.
- The recommended practice is to open a context per action because once an item is added to the DB your context Is outdated and might cause data corruption or duplicated items
Does the size of the Edmx effects this?
- The size of Edmx affects the first creation of the context since all the Edmx data is loaded into memory.
- The EDMX is loaded into the memory, parsed, and the mapping is created and cached in the AppDomain. You can close and reopen contexts without it affecting the cached Edmx mappings.
Working with large number of tables
Should all the tables be put in a single Edmx or split between several Edmx files?
How one can manage an edmx with large number of entities? for example, how one can find?
and modify a specific table in the designer?
- If you split between Edmx files, you cannot connect entities one to the other (navigation properties).
You should build your model according to your entity model design – if you have groups of entities which are independent they can be in separate Edmx models.
EDMX files are known to handle a couple of hundreds of entity types. If the number of entity types is over 1000, I would consider splitting to several Edmxs (and rethink your entity model design, because thousands of entity types seems too much for one system). - Move to VS 2012 in order to have designer enhancements like split and coloring, see the following link.
- The EF designer has several improvements, such as coloring entities to differentiate entities groups.
There are also 3-rd party entity designers that might give better UX.
And remember – EF is an open source, you can send them requests and even contribute your own additions to it, so search in EDMX designer sounds interesting. - you should split the Edmx to couple of Edmx files per domain/service.
Relationships between tables
Working in lazy vs. not lazy mode?
- In general Lazy code is evil for distributed scenarios.
- If they need data from couple of tables then use Include else you can use lazy loading.
Does the "Include" command load the entire table or only the records related to the original ObjectSet?
- Include loads the columns of the related entity. EF doesn't use * in queries.
How can we perform bulk insert/update using EF?
- You cannot do it with EF entities, you need to use raw SQL.
When an entity is marked as modified, EF updates all the columns?
- It doesn't update all the columns, unless you are using distributed apps with self-tracking. The "normal" implementation of EF only updates modified columns. With self-tracking the mechanism does not keep track of which property was updated, so it marks all properties as updated. You can edit the self-tracking code and fix it if it's required.
- You can attach SP in order to have a custom logic.
- You can change the T4 file in order to maintain all original values in self-tracking scenario.
What's the overhead of entire raw updating?
- Mostly DB overhead to recalculate indexes I presume. This is more a question to a DBA.
When we used EF to update an XML column with XML file which is 700-800KB, We received an exception related to Sql Server's TempDb. what can cause it?
- Probably relates to how the database works with temporary tables for updating XML content.
You should have your database checked out by a DBA, perhaps you need to increase the size of your TempDb. - In general large object like those Xml will make a memory pressure on the GC's Large Object Heap, you should consider to move to .NET 4.5 where the GC does defragment the Large Object Heap.
- You can consider to store the XML as byte[] which can be compressed (Xml is not a very economic format).
What's the overhead of using EF vs. ADO.Net?
- The overhead of taking a data reader an transforming the results to objects, and the overhead of compiling SQL queries from LINQ.
You will have the same overhead and even more, if you try to build your own ORM framework. Don’t do that! - When you have abstraction layer you get overhead. The overhead depends on what they do with EF.
- in general you should conceder to get away from Inheritance because it does have a greater overhead.
Credits:
I want to credits the main contribution for this conversation which was Ido Flatow, Gil Fink, Yaniv Rodenski, Amit Raz, Ofir Makmal, Tomer Shaiman and I'm hopping that I didn't miss anyone.
MEF 2.0 - mini series: part 4 (Fluent Import)
this is the 4th post in the
MEF 2.0 mini series.
you can see the following
TOC for other posts in this series.
in this post I will discuss the Fluent import API.

we was talking about Fluent Export and Constructor Injection in the previous posts. this post will complete the main scenarios of Import's fluent API.
I will demonstrate the import technique using the following classes:
Code Snippet
- public class Foo
- {
- public Logger Log { get; set; }
- }
-
- public class Logger
- {
- public void Write(string message) { /* ... */ }
- }
we can Export both classes by one of the fluent techniques which we discuss in previous posts, for example:
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForType<Logger>()
- .Export<Logger>();
- picker.ForType<Foo>()
- .Export();
-
- var catalog = new AssemblyCatalog(typeof(Foo).Assembly, picker);
- var container = new CompositionContainer(catalog);
but this is not enough, because Foo's Log property has no [Import] attribute, therefore it will be ignored by the composition.
using the fluent ImportProperties, you can introduce it into the composition :
Code Snippet
- picker.ForType<Foo>()
- .Export()
- .ImportProperties<Logger>(pi => pi.Name == "Log");
the property's Type is referred by the generics parameter while the Lambda used for filtering the target properties.
actually you can take it further and configure the import behaviors.
for example you can set the import to Allow Default:
Code Snippet
- picker.ForType<Foo>()
- .Export()
- .ImportProperties<Logger>(pi => pi.Name == "Log",
- (propInfo, builder) => builder.AllowDefault());
it's consider as best practice to Allow Default and implement IPartImportsSatisfiedNotification interface which is an interception point which occurs right after the composition.
the idea is to check the composition state within the OnImportsSatisfied()
method in order to verify the composition state.
It is true that MEF exceptions have made better, but it still not perfect and sometimes it is really hard to trace the root cause of the exception. implementation of IPartImportsSatisfiedNotification will make the tracing easier.
so what about Select Many?
let change our Foo class to the following code:
Code Snippet
- public class Foo: IPartImportsSatisfiedNotification
- {
- public Logger[] Log { get; set; }
-
- public void OnImportsSatisfied()
- {
- }
- }
the following code will define the Log property as [ImportMany]:
Code Snippet
- picker.ForType<Foo>()
- .Export()
- .ImportProperties<Logger>(pi => pi.Name == "Log",
- (propInfo, builder) => builder.AsMany());
as you can see we are using the same overload that can manipulate the Import's behaviors.
by the same technique you can define a re-composition and the creation policy:
Code Snippet
- picker.ForType<Foo>()
- .Export()
- .ImportProperties<Logger>(pi => pi.Name == "Log",
- (propInfo, builder) =>
- {
- builder.AsMany();
- builder.AllowRecomposition();
- builder.RequiredCreationPolicy(CreationPolicy.NonShared);
- });
summary
fluent Import is complimentary to fluent Export.
it's fairly flexible API which enable to assign your own or 3rd party class's properties.
actually you can take a 3rd party class and inject it's public properties through those techniques.
MEF 2.0 - mini series: part 3 (Fluent import constructor)
this is the 3rd post in the MEF 2.0 mini series.
you can see the following TOC for other posts in this series.
in this post I will discuss the fluent constructor injection API.

Constructor Injection
the following code is having a Logger and Worker class which is having 2 constructor (one has no parameters and the other is getting ILogger):
Code Snippet
-
- public class Logger: ILogger
- {
- public void Write(string message) { /* ... */}
- }
-
- public class Worker
- {
- private ILogger _logger;
-
- public Worker()
- {
- /* ... */
- }
-
- public Worker(ILogger logger)
- {
- _logger = logger;
- }
- }
the question is, which of the construction will be invoked by the following code?
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForTypesDerivedFrom<ILogger>()
- .Export<ILogger>();
- picker.ForType<Worker>()
- .Export();
-
- var catalog = new AssemblyCatalog(typeof(Program).Assembly, picker);
- var container = new CompositionContainer(catalog);
- container.Compose(new CompositionBatch());
- var w = container.GetExportedValue<Worker>();
the code Export the Logger and the Worker but doesn't define explicitly which of the Worker's construction should be invoke.
the answer is that it will invoke the constructor that is getting the ILogger parameter, but could we be more precise?
actually we do have 2 different options.
first option is to use SelectConstructor before the Export method.
see the following code:
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForTypesDerivedFrom<ILogger>()
- .Export<ILogger>();
- picker.ForType<Worker>()
- .SelectConstructor(builder => new Worker(builder.Import<ILogger>()))
- .Export();
-
- var catalog = new AssemblyCatalog(typeof(Program).Assembly, picker);
- var container = new CompositionContainer(catalog);
- container.Compose(new CompositionBatch());
- var w = container.GetExportedValue<Worker>();
this way we can define an expression that define which constructor should be invoke.
the expression is getting a ParameterImportBuilder which I used to define the logger (builder.Import<ILogger>()).
the next option is to set the SelectConstructor after the Export.
now we are getting a ConstructorInfo[] and we can select a single constructor out of this array.
ConstructorInfo
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForTypesDerivedFrom<ILogger>().Export<ILogger>();
- picker.ForType<Worker>()
- .Export()
- .SelectConstructor(ctors =>
- ctors.First(info => info.GetParameters().Length == 1));
the code select a constructor which is having a single parameter, but the real implementation is up to you. you can ask on whatever constructor's aspect which you like to.
Summary
as cool as it is to control the constructor injection using the fluent API,
you may consider to use imported properties rather than constructor injection because it can be more stable is during the composition state and can apply on more scenarios, including implementation of IPartImportsSatisfiedNotification.
MEF 2.0 - mini series: part 2 (Fluent and Conventional Export)
this is the second post in the MEF 2.0 mini series.
you can see the following TOC for more.
in this post I will start to cover the fluent discovery model and the idea of discovery by convention.

traditionally, out of the box, MEF come with a single discovery model, which was the Attribute model.
it is true that you could extend MEF's discovery model by using either a custom catalog or a custom export provider, but this task wasn't as simple as the MEF 2 fluent discovery model and therefore wasn't a common practice.
Registration Builder
MEF 2.0 is having the new RegistrationBuilder class which can be used to apply a custom picker (filter) for specific types within the scope of a catalog.
the idea is that the catalog will apply a sandbox which is a searching area scope (like Assembly, Directory, ext...), while the registration builder will pick up the relevant exported part within the scope.
actually the catalog will compose both the old attribute model and the picked up types.
this technique can be used either as a replacement for the Attribute model or as a complementary for 3rd party types which we cannot recompile with the [Export] attribute.
in order to work with the registration builder, you should add reference to
- System.Reflection.Context
- System.ComponentModel.Composition
- System.ComponentModel.Composition.Registration
at its simplest form it can be used to append a specific type into the composition.
Code Snippet
- static void Main(string[] args)
- {
- Program p = new Program();
-
- var picker = new RegistrationBuilder();
- picker.ForType<AesManaged>()
- .Export<SymmetricAlgorithm>();
-
- var catalog = new TypeCatalog(
- new []{typeof(AesManaged)}, picker);
-
- var container = new CompositionContainer(catalog);
- container.ComposeParts(p);
- }
-
- [Import]
- private SymmetricAlgorithm Crypto { get; set; }
the above code exporting the AesManaged cryptography algorithm as a symmetric crypto algorithm.
currently the Import is still using the old Attribute model. I will show you how to define a fluent Imports in future post.
another aspect that you can control is the instantiation strategy by using the SetCreationPolicy:
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForType<AesManaged>()
- .Export<SymmetricAlgorithm>()
- .SetCreationPolicy(CreationPolicy.NonShared);
in future post I will talk about creation scope and lifetime, which is a fine tuning option for the part lifetime control.
Export inheritance
you can choose to export anything that derived from a Type or implement an Interface:
Code Snippet
- picker.ForTypesDerivedFrom<SymmetricAlgorithm>()
- .Export<SymmetricAlgorithm>()
- .SetCreationPolicy(CreationPolicy.NonShared);
Export by conventions
a common IoC strategy is to discover extensions by convention.
for example loading all the type with a 'Plugin' suffix.
this strategy reduce the maintenance of either xml files or bootstrapper code.
this type of discovery made easy in MEF 2.0.
the following code is loading any type which is ending with a 'Plugin' extension into the composition.
Code Snippet
- picker.ForTypesMatching(pl => pl.Name.EndsWith("Plugin"))
- .ExportInterfaces();
as you can see that the code is exporting all of the interfaces that was implemented by the plugins.
foe example, if you are having the following interfaces and implementation:
Code Snippet
- public interface ILogPlugin
- {
- void Write(string message);
- }
- public class LoggerPlugin : ILogPlugin
- {
- public void Write(string message) { /* ... */}
- }
-
- public interface ISavePlugin
- {
- void Save(string message);
- }
- public class FilePlugin : ISavePlugin
- {
- public void Save(string message) { /* ... */}
- }
LoggerPlugin will be export as ILogPlugin and FilePlugin will be export as ISavePlugin.
ExportInterfaces is having a few overloads which you can use to refine the interface exporting, instead of exporting all of the implemented interfaces, you can define a convention, for example:
Code Snippet
- picker.ForTypesMatching(pl => pl.Name.EndsWith("Plugin"))
- .ExportInterfaces(t => t.Name.EndsWith("Plugin"));
Summary
MEF 2.0 fluent and conventional model is a great improvement over the Attribute model. as you can see you can use both model together, but the convention model can ease your maintenance.
in the next post I will discuss it further.
MEF 2.0 TOC
MEF 2.0 is a reflection of a community requests.
features like Open Generics, fluent and conventional discovery, lifetime handling of the part, better exception handling and more, was all requested by the community.

you can read more about MEF 1 series:
MEF 2.0 - mini series: part 1 (Open Generics)
this is the first post of a new mini series about MEF 2.0.
MEF 2.0 is a reflection of a community requests.
features like Open Generics, fluent and conventional discovery, lifetime handling of the part, better exception handling and more, was all requested by the community.
each post of this mini series will target a single enhancement.

Open Generics
one of the most annoying missing feature in MEF 1 was the lack of support for Open generics.
the following code (which is fully functioning in MEF 2.0) didn't worked in MEF 1.
Code Snippet
- public class Foo
- {
- [Import]
- public EventAggregator<int> IntAggregator { get; set; }
- }
-
- [Export]
- public class EventAggregator<T>
- {
- public event Action<T> Notify = (item) => { };
- public void Send(T item)
- {
- Notify(item);
- }
- }
as obvious as it may seem, this piece of functionality is missing in MEF 1.
if you try to do it in MEF 1 it will look like the following code:
Code Snippet
- public class Foo
- {
- [Import]
- public EventAggregatorInt IntAggregator { get; set; }
- }
-
- [Export]
- public class EventAggregatorInt : EventAggregator<int> { }
-
- public class EventAggregator<T>
- {
- public event Action<T> Notify = (item) => { };
- public void Send(T item)
- {
- Notify(item);
- }
- }
it is quite obvious that extra EventAggregatorInt class shouldn't have be been there in the first place.
Summary
Open Generics if fairly straight forward and it is keeping our code smaller and better.