MEF——有什么方法可以用参数初始化它吗?
[Export]
public class MyViewModel : NotificationObject
{
public MyViewModel(Foo foo)
{
DoWorkCommand = new DelegateCommand(DoWork);
MyFoo = foo;
}
[Import]
private IBarService MyBarService { get; set; }
public Foo MyFoo { get; private set; }
public DelegateCommand DoWorkCommand { get; set; }
public void DoWork()
{
MyBarService.DoSomething(MyFoo);
}
}
如何获取 MyViewModel 类的实例,同时还能传入参数?我想也许 ExportFactor
会让我传递一些参数,但事实并非如此。那么,是否有某种模式可以解释我希望实现的目标?
简单地执行 new() 并不能解决问题,因为此时 MyBarService
仍为 null。我考虑过删除 ExportAttribute
并使用 ComponentInitializer.SatisfyImports(this)
,这让我可以使用 new(),但这使得我必须 new()一切。我有点希望两全其美......有某种类型的方法来导入带有参数的东西。这样我仍然是解耦的,但能够使用设置的参数生成 ViewModel 的实例。
[Export]
public class MyViewModel : NotificationObject
{
public MyViewModel(Foo foo)
{
DoWorkCommand = new DelegateCommand(DoWork);
MyFoo = foo;
}
[Import]
private IBarService MyBarService { get; set; }
public Foo MyFoo { get; private set; }
public DelegateCommand DoWorkCommand { get; set; }
public void DoWork()
{
MyBarService.DoSomething(MyFoo);
}
}
How can I get an instance of the MyViewModel class while also being able to pass in parameters? I thought maybe the ExportFactor<T>
would let me pass in some parameters, but it doesn't. So, is there some pattern that accounts for what I'm hoping to achieve?
Simply doing a new() won't cut it because the MyBarService
stays null then. I thought about removing the ExportAttribute
and using ComponentInitializer.SatisfyImports(this)
, which let's me use new(), but that kind of makes it so I have to new() everything. I was kind of hoping for a best of both worlds... having some type of way to Import something with parameters. That way I am still decoupled, but am able to generate instances of my ViewModel with the parameters set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MEF 支持依赖注入,例如,我可以这样做:
MEF 会自动尝试将
Foo
实例注入到我的构造函数中。也许您可以使用这种机制将所需的服务注入到您的组合部件中?MEF supports depedency injection, for instance, I could do:
And MEF will automatically try and inject an instance of
Foo
into my constructor. Perhaps you could use this mechanism to inject your required services into your composed parts?如果您想将一些参数从导入器传递到导出器,那么您可以在要导出的类或接口上放置一个 Initialize 方法。像这样的事情:
然后在导入端使用
ExportFactory
,并在创建导出的新实例后调用Initialize
方法。If you want to pass some parameters from the importer to the exporter, then you can put an Initialize method on the class or interface you are exporting. Something like this:
Then use an
ExportFactory
on the import side, and call theInitialize
method after creating a new instance of the export.