使用PartCreationPolicy的MEF属性导出 [英] MEF Property Export with PartCreationPolicy

查看:85
本文介绍了使用PartCreationPolicy的MEF属性导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试这样做时:

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

我收到一个编译错误:Attribute 'PartCreationPolicy' is not valid on this declaration type. It is only valid on 'class' declarations.

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

这是一个错误吗?我不明白为什么MEF会允许财产出口,却不允许人指定零件寿命.

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

使用VS2010 RC.

Using VS2010 RC.

推荐答案

即使对属性进行导出,PartCreationPolicy也应继续在类上.该类就是与零件对应的类,并且创建策略将控制MEF是否在每次请求导出时都创建该类的新实例.

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.

我不确定您要使用共享"还是非共享".在代码示例中,您已将CreationPolicy设置为Shared,但是随后您将在属性getter中创建MyService的新实例.这似乎表明您可能正在寻找非共享的创建策略.

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.

如果确实希望每次请求导出时都创建新服务,则应通过创建策略(而不是通过在getter中创建新实例)来进行.导出的值不应在运行时更改,实际上MEF只会调用一次getter,并在需要再次访问导出的值时存储返回值.因此,在您的getter中创建一个新实例可以使实际上只有一个实例的情况下会创建多个服务.

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.

这篇关于使用PartCreationPolicy的MEF属性导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆