MEF: Passing different constructor parameters to a part when using CreationPolicy.NonShared

Mar 30, 2012 at 5:16 PM
Edited Mar 30, 2012 at 5:18 PM

I know there have been lot of questions regarding constructor parameter injection using MEF, but mine is a bit different.

I want to know that is there any way to pass different parameter values to the constructor of a part when I am using the combination of PartCreationPolicy(CreationPolicy.NonShared) and GetExportedValue?

For example:

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export]
public partial class Foo
{
   
[ImportingConstructor]
   
public Foo([Import("SomeParam")]object parameter)
   
{
       
...
   
}
}

and somewhere else...

container.ComposeExportedValue("SomeParam", "Some value...");
var instance = container.GetExportedValue<Foo>();

In the above example, I can use ComposeExportedValue only once, as running it a second time will cause a ChangeRejectedException

So, my questions are:

  1. Is there any other way to change the value of SomeParam in the above scenario, for each new instance?
  2. If not, what are the other ways this can be accomplished without using any other DI framework? One thing which comes to mind is to create a service to expose something likeSystem.Collections.Concurrent.ConcurrentQueue where I enqueue a parameter value before calling GetExportedValue and then dequeue the value in the constructor of the part. But that is a hack and also creates more issues than it solves.

Thanks for any help. :)

Regards,
Yogesh Jagota