将自定义容器添加到 MEF
我有以下使用 MEF 的案例。
我通过许多模块构建我的解决方案,每个模块都存在于不同的 dll 中。我选择使用 MEF 来编写我的所有项目。 它工作正常,但有时我为模块添加一个服务类(AppService),该类仅具有处理该特定模块的通用服务的自定义静态方法。现在,在这个方法中,我需要一些已经在 MEF 中组成的服务。 MEF 容器已存在于邮件 shell 程序中。 如何获得我需要的参考资料。如果我使用[导入],它不起作用。 示例:
public class AppService
{
[Import]
public IService MyService {get;set;}
public static int Calc()
{
return MyService.Calc(); //My service is null
}
}
提前致谢...
I have the following case using MEF .
I build my solution by many modules, each module exists in a different dll . I use MEF as a choice to compose all my project.
Its works fine , but sometimes I add for a module a service class say (AppService), this class simply has custom static methods which deal with generic service of this specific module . Now in this method I need some service which allready composed in MEF. The MEF container allready exists in the mail shell program .
How can get reference to the reference I need . if I use [Import] it doesn't work.
Example :
public class AppService
{
[Import]
public IService MyService {get;set;}
public static int Calc()
{
return MyService.Calc(); //My service is null
}
}
Thanks in advance ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您的代码实际上存在一些问题。
1.您是否确认您的
AppService
类型正在被组合?由于您没有[Export]
-ing它,所以我看不到它是如何生成的。如果您没有从容器中获取AppService
实例,则必须手动满足导入:2.您的类设计有一个
static
方法,您试图在其中访问实例
属性。我假设您尝试这样做有两个原因之一。或者,您假设 IService 的接口支持静态操作(它们不能),或者您正在调用支持 IService 的扩展方法> 类型,失败是因为可疑扩展方法的第一个参数为 null:如果是后一种扩展方法场景,它会建议类似于 1) 的内容,您需要确认您的
AppService
类型在实例化后正在组合。事实上,您有一个
static
方法试图访问instance
属性,这会告诉我您可能需要重新考虑您的设计,并删除static
> 修饰符:但是,你的属性是公共的,那么这个方法有什么用呢? 您当前的示例甚至不应该编译,因为您正在尝试从静态方法访问实例属性。
I think you actually have a few problems with that code.
1.Have you confirmed that your
AppService
type is being composed? As you are not[Export]
-ing it, I can't see how that is generated. If you are not grabbing an instance ofAppService
from the container, you have to manually satisfy the imports:2.Your class design has a
static
method, where you are trying to access aninstance
property. I'm assuming you're trying that for one of two reasons. Either, you assume theinterface
forIService
supports static operations (which they can't), or you are calling an extension method that supports theIService
type, which is failing because the first argument of the suspected extension method is null:If it is the latter extension method scenario, it would suggest something similar to 1) where you need to confirm that your
AppService
type is being composed after it is instantiated.The fact you have a
static
method trying to access aninstance
property would tell me that you probably need to rethink your design anyway, and remove thestatic
modifier:But again, your property is public, so is this method of any use at all? You current example shouldn't even compile, as you are trying to access an instance property from a static method.