Just wanted to know if what I’m trying to do is possible since I couldn’t find any information about it in the net.
Lets say I got a class that I export with PartCreationPolicy(CreationPolicy.Any).
If I’d like to import it with ServiceLocator.Instance.GetInstance(), where can I specify with which CreationPolicy I’d like to import it? (If it would be Shared or NonShared)
Just couldn’t find any info about it anywhere.
Thanks!
As I understand it this can’t be specified through a generic service locator.
By default,
CreationPolicy.Anywill be treated as ‘shared’. To get a ‘non-shared’ instance you need to either:CreationPolicy.NonShared; or,CompositionContainer.GetExports(ImportDefinition)method; or,ExportFactoryimport and request that from theServiceLocator(see below. Requires MEF 2, or Silverlight 4 – not available in the .NET 4.0 RTM MEF.)The kind of thing you need for the third option would look like:
Then, request one of these from the service locator and use the factory property to create new instances (where
IServiceis the thing you want to instantiate new instances of):Admittedly this ends up looking a bit hacky. I believe the reason for the awkwardness is that few (no?) other IoC containers support specifying anything like
CreationPolicywhen a service is requested.