Export/Import CreationPolicy from code?

Oct 17, 2009 at 9:34 PM

Is there a way to specify the Export-CreationPolicy and Import-RequiredCreationPolicy without the use of the attributes (from code)?

// example:
CompositionBatch batch = new CompositionBatch();
batch.AddExportedValue<CompositionContainer>(container);
batch.AddExportedValue<IMessageBoxService>(new StandardMessageBoxService());
batch.AddExportedValue<ISettingsService>(new StandardSettingsService());

// and somewhere else in the code...
ISettingsService settingsService = container.GetExportedValue<ISettingsService>();

I want NonShared for the IMessageBoxService and Shared for ISettingsService? The reason I needed to do it from code is what if I'm unable to modify the dll library where the StandardMessageBoxService and StandardSettingsService lives in?

Thanks.

Developer
Oct 18, 2009 at 7:47 PM

When you add an object instance via a CompositionBatch the Export/Part is always automatically Shared. The reason for this is because if it were NonShared the container would need to know how to construct a new instance and it doesn't have the context to have that knowledge.

If you really want a NonShared of a type, which you don't control the source code for, I can see only two possible approaches:
1) Instead of adding IMessageBoxService you could add an IMessageBoxServiceFactory which could create as many instances as needed, but the Import would then have to import IMessageBoxServiceFactory instead and call the create method for it.
2) You could create a custom catalog that could wrap the type in a ComposablePartDefinition which defined all the behavior you wanted for that particular type. While this would give you the most flexibility and would still allow the importer to import IMessageBoxService it requires more work upfront in constructing a custom catalog.

So depending on your particular scenario you can make a choice. Another potential solution if this really is only for StandardMessageBoxService is to create a subclass of StandardMessageBoxService that you can control the source and place the attributes on it.

Oct 18, 2009 at 7:58 PM

An alternative apporach is the one that Dave described on his blog. He shows you how to create a custom container which requests non-shared exports by default. You could even write a custom ExportProvider to do this rather than having to create a new container. The post is on  older bits, but you could update the code to work with Preview 7.

http://davesbox.com/archive/2009/02/07/changing-default-creation-policy-from-shared-singleton-to-non-shared-transient.aspx

Regards

Glenn