Quantcast
Channel: Managed Extensibility Framework
Viewing all articles
Browse latest Browse all 265

New Post: Use MEF to allow only 2 instances at max per application

$
0
0
I am using MEF as an IOC in my application. I found myself stuck in a situation where I need exactly two instance at a time for a class in my application (across all threads). I thought it would be easy just by adding export attribute twice with different container name and then using that container name to create two instances.
[Export("Condition-1",typeof(MyClass)]
[Export("Condition-2",typeof(MyClass)]
[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)]
public class MyClass  {   }
And then get export as
Container.GetExport<MyClass>("Condition-1").Value
Container.GetExport<MyClass>("Condition-2").Value
But this trick did not work. CreationPolicy is ignoring the ContractName and is returning one instance no matter what contract name i use in GetExport. I finally able to solve my problem by using CompsositionBatch
cb.AddExportedValue<MyClass>("Condition-1",new MyClass());
cb.AddExportedValue<MyClass>("Condition-2",new MyClass());
But my question is, Why am I not able to get different instances on the basis of Contract Name. Is it right that Contract name does not matter if CreationPolicy is shared?

Viewing all articles
Browse latest Browse all 265

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>