MEF -- Any way to initialize it with parameters?
[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.
MEF supports depedency injection, for instance, I could do:
[ImportingConstructor]
public MyViewModel(Foo foo)
{
}
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?
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:
[Export]
public class MyViewModel : NotificationObject
{
public MyViewModel()
{
DoWorkCommand = new DelegateCommand(DoWork);
}
public void Initialize(Foo foo)
{
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);
}
}
Then use an ExportFactory
on the import side, and call the Initialize
method after creating a new instance of the export.
精彩评论