从 MEF 容器获取导出的零件实例
我如何获取 MEF 容器中导出零件的现有实例。如果我有在容器中组成的类 A,我需要在代码中的某些地方获取实例,如果我调用 GetExortedValue() ,那么如果类 A 使用 CreationPolicy.NonShared 签名,那么它将再次实例化并且我需要当前的一份。
提前致谢 ...
How I can the existing instance of an exported part in MEF container . If I have class A which was composed in the container , I need in some places in my code to get the instance , if I call GetExortedValue() , then if class A signed with CreationPolicy.NonShared , then it'll be instantiated again and I need the current one .
Thanks in advance ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显然,在容器上调用
GetExportedValue
可能会导致生成T
的新实例(取决于该部分使用的CreationPolicy
) ),但有一个选项可以调用GetExport
,它将返回一个Lazy
实例。这是生成的单一部分,并且仅生成一次:在上面的示例中,
part
将是Lazy
的实例,因此当您第一次访问 < code>part.Value,Lazy
中绑定的委托回调容器以创建和组合IMyInterface
实例并返回。对part.Value
的后续调用将始终返回同一实例。Obviously calling
GetExportedValue<T>
on your container could result on the generation of a new instance ofT
(depending on theCreationPolicy
used for the part), but there is an option to callGetExport<T>
which will return you aLazy<T>
instance. This is the singular part that is generated and only generated the once:In the above example,
part
would be an instance ofLazy<IMyInterface>
, so when you first accesspart.Value
, the delegate bound in theLazy<IMyInterface>
calls back to the container to create and compose theIMyInterface
instance and is returned. Subsequent calls topart.Value
will always return this same instance.