Reputation: 1901
I need to use MEF and MVVM pattern for my WPF app.
Actually I have a ViewModel so definied:
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
class MainVM
{
IServiceA serviceA;
IServiceB serviceB;
[ImportingConstructor]
public MainVM(IServiceA serviceA, IServiceB serviceB)
{
this.serviceA = serviceA;
this.serviceB = serviceB;
System.Diagnostics.Debug.WriteLine(serviceA.Time);
}
}
For the VM retrieving, I make use of a VMLocator, so made:
class ViewModelLocator
{
static ViewModelLocator instance;
public MainVM MainVM
{
get
{
MainVM output = MefBootstrap.Container.GetExportedValue<MainVM>();
return output;
}
}
protected ViewModelLocator()
{
}
public static ViewModelLocator Instance
{
get
{
return instance ?? (instance = new ViewModelLocator());
}
}
}
called from XAML:
DataContext="{Binding Source={x:Static provider:ViewModelLocator.Instance}, Path=MainVM}"
This code actually works.
What I wonder if realizable is to automatically Import VM using only MEF ExportAttribute [Import] on the attribute declaration of VMLocator instead of using GetExportValue() method.
Is the any solution ?
Upvotes: 0
Views: 277
Reputation: 1543
It does not work because you manually create ViewModelLocator
. Since you create it manually IoC(MEF) does not have control over this instance creation and thus it will not [Import]
dependency(MainVM
) from container into your property
.
So to address the question "Is there any solution?":
Here is an example of how to leverage MEF in MVVM context.
I strongly advice you go with PRISM. It already has it done for you. I'd rather not reinvent the wheel especially this one.
Upvotes: 1