使导入可用在您的代码周围
在我的 MEF 用法中,我有一堆导入,我想在许多其他部分使用它们我的代码。 就像:
[Export (typeof (IBarProvider))]
class MyBarFactory : IBarPovider
{
[Import]
public IFoo1Service IFoo1Service { get; set; }
[Import]
public IFoo2Service IFoo2Service { get; set; }
[Import]
public IFoo3Service IFoo3Service { get; set; }
[Import]
public IFoo4Service IFoo4Service { get; set; }
[Import]
public IFoo5Service IFoo5Service { get; set; }
public IBar CreateBar()
{
return new BarImplementation(/* want to pass the imported services here */);
}
}
class BarImplementation : IBar
{
readonly zib zib;
public BarImplementation(/* ... */)
{
this.zib = new Zib(/* pass services here, too */);
}
}
我可以将每个导入的服务作为单独的参数传递,但这是很多无聊的代码。 一定有更好的东西。 有任何想法吗?
In my MEF usage, I have a bunch of imports that I want to make available in many other parts of my code. Something like:
[Export (typeof (IBarProvider))]
class MyBarFactory : IBarPovider
{
[Import]
public IFoo1Service IFoo1Service { get; set; }
[Import]
public IFoo2Service IFoo2Service { get; set; }
[Import]
public IFoo3Service IFoo3Service { get; set; }
[Import]
public IFoo4Service IFoo4Service { get; set; }
[Import]
public IFoo5Service IFoo5Service { get; set; }
public IBar CreateBar()
{
return new BarImplementation(/* want to pass the imported services here */);
}
}
class BarImplementation : IBar
{
readonly zib zib;
public BarImplementation(/* ... */)
{
this.zib = new Zib(/* pass services here, too */);
}
}
I could pass each imported service as an individual parameter, but it's a lot of boring code. There's gotta be something better. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不完全确定这能回答您的问题,但您是否考虑过使用构造函数注入?
通过使用 ImportingConstructor 属性标记构造函数,它实际上会使该构造函数的所有参数都需要导入。
I'm not entirely sure this answers your question but have you considered using the constructor injection yet?
By marking your constructor with the ImportingConstructor attribute it will essentially make all the parameters of that constructor required imports.
我考虑过创建一个接口来提供这些服务:
然后
MyBarFactory
实现BarImplementation : BarImplementation.IRequiredServices
。 这很容易编写,但是如何将它们传递给Zib
呢? 我不想以这种方式将Zib
与其消费者耦合。I thought about making an interface to provide these services:
Then
MyBarFactory
implementsBarImplementation : BarImplementation.IRequiredServices
. That's easy to write, but then, how do I pass them down toZib
? I don't want to coupleZib
to its consumer that way.我可以使 IImports 成为一个包含我导入的所有服务的接口,将其传递到各处,然后类可以使用或不使用它们喜欢的任何一个。 但这将所有类结合在一起。
I could make
IImports
an interface that contains all the services I import, pass that around everywhere, and then classes can use or not use whichever they like. But that couples all the classes toegether.