Reputation: 991
i'm using Prism-MEF-WPF and Sometimes i need view model gets constructed from the XAML of the view, so the container is not involved and can’t do the dependency injection automatically (as there is no Export attribute used with VM).so there should be some class in Prism-WPF like CompositionInitializer to enable me to ask the container to do the injection.In case there is equivalent class how to use it, and in case there is no equivalent how to construct view model from xaml of the view knowing that i use MEF. Thanks in advance.
Upvotes: 1
Views: 579
Reputation: 991
Here is the right answer which i got from Agustin Adami "http://blogs.southworks.net/aadami":
Based on my understanding the view model can be instantiated in XAML as the view’s DataContext only if a view model does not have any constructor arguments. And as far as I know creating objects defined in XAML by partnering with an Inverse of Control Container is currently not supported.
Regarding the CompositionInitializer class, as far as I know there is no equivalent class for WPF, on the other hand regarding this topic, I believe you could find the following blog post interesting:
https://web.archive.org/web/20230128075959/http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/ Also, I believe an alternative for this could be registering the CompositionContainer class like mentioned in this thread:
http://compositewpf.codeplex.com/discussions/311933 As this could let you retrieve this class for example in your view model's constructor, in order to call the SatisfyImportsOnce method to satisfy the Imports defined in the passed class:
this.compositionContainer =ServiceLocator.Current.GetInstance(); this.compositionContainer.SatisfyImportsOnce(this);
Upvotes: 1
Reputation: 16648
The problem is that you can't create an object in XAML if it doesn't have a parameterless constructor.
Using the ServiceLocator, you can achieve this. It will work as an IoC (and is set up by Prism/MEF, you just have to drop the .dll):
The xaml:
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
The code-behind:
class ViewModel : NotificationObject
{
public ViewModel()
{
var firstDependency = ServiceLocator.Current.GetInstance<FirstDependencyType>();
//... more dependencies here instead of as constructor parameters
}
//class code omitted for brievity
}
Upvotes: 1
Reputation: 81253
Bootstrapper class is what you are looking for. It uses UnityContainer
for injecting dependencies. This link here might be of your interest too..
EDIT
If i am getting right, you want to create a ViewModel from your xaml which can be achieved like this(Here local is namespace of your ViewModel class) -
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
Upvotes: 0