开发者

MEF Property Export with 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 compile error: Attribute 'PartCreationPolicy' is not valid on this declaration type. It is only valid on 'class' declarations.

Is this a bug? I don't see why MEF would allow property exports but not allow one to specify the part lifetime.

Using VS2010 RC.


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

I am not sure whether you want to use Shared or NonShared. You have the CreationPolicy set to Shared in your code example, but then you are creating a new instance of MyService in your property getter. That seems to indicate you may be looking for a creation policy of NonShared.

If you do want a new service to be created each time an export is requested, you should do it via the creation policy, and not by creating a new instance in the getter. The value of an export is not supposed to change at runtime, and in fact MEF will only call the getter once, and store the return value for when it needs to access the exported value again. So creating a new instance in your getter can make it look like there would be multiple services created when there will actually only be one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜