Export MEF Property Using PartCreationPolicy

When I try to do this:

[Export(typeof(IMyService))] [PartCreationPolicy(CreationPolicy.Shared)] private MyService Service { get { var service = new MyService(); service.Configure(); return service; } } 

I get a compilation error: Attribute 'PartCreationPolicy' is not valid on this declaration type. It is only valid on 'class' declarations. Attribute 'PartCreationPolicy' is not valid on this declaration type. It is only valid on 'class' declarations.

This is mistake? I don’t understand why MEF allows the export of properties, but it does not allow specifying the life time of a part.

Using VS2010 RC.

+4
source share
1 answer

PartCreationPolicy should go to the class, even if the export goes to the property. The class corresponds to what corresponds to the part, and the creation policy will determine whether the MEF will create a new instance of the class each time an export is requested from it.

I'm not sure if you want to use Shared or NonShared. You have CreationPolicy set to Shared in your sample code, but then you create a new instance of MyService in your getter. This seems to indicate that you can look for NonShared's creation policy.

If you want to create a new service every time you request an export, you must do this using the create policy, and not by creating a new instance in getter. The export value should not change at run time, and in fact, the MEF will only call once, and save the return value when it needs to access the exported value again. Thus, creating a new instance in your recipient can make it look as if several services were created, when in fact there will be only one.

+7
source

Source: https://habr.com/ru/post/1307338/


All Articles