I have been experimenting MEF and MVVM. I wanted to let MEF initialize a NonShared ViewModel instance with a string constructor parameter, i.e something like this:
// BarViewModel's constructor has one single string parameter
IBarViewModel bar = container.GetExportedValue<IBarViewModel>("bar title");
Obviously MEF wouldn't let me do this.
I googled and some say ExportFactory is the right tool for this but there are no syntax samples. I have not been able to figure out how to use ExportFactory to initialize an instance with constructor parameters (or should I say non-imported parameter).
So then I tried to use a ViewModelFactory to achieve this. I referenced this article
and came up something like this:
[Export(typeof(IBarViewModelFactory))]
public class BarViewModelFactory : IBarViewModelFactory
{
[Import]
public Lazy<CompositionContainer> Container { get; set; }
public IBarViewModel CreateBarViewModel(string text)
{
IBarViewModel result = null;
var tempContainer = CreateTemporaryDisposableContainer(Container.Value);
try
{
result = new BarViewModel(text);
tempContainer.ComposeParts(result);
}
catch (Exception ex)
{
}
finally
{
}
return result;
}
Basically what I'm doing here is (1) import a Container from somewhere else (2) new the VM up with parameter (3) use a temporary container to settle the dependencies of the new'ed instance.
This code seems working OK but I then discovered that (a) BarViewModel can no longer have [ImportingConstructor] (b) I cannot use [Import] properties of BarViewModel in its constructor because they are null in the ctor scope.
This mean the ViewModel is very limited in usage and also it means it is not possible to initialize a class like this with MEF:
[Import]
public ILogger Logger {get;set;}
[ImportingConstructor]
public SomeClass(IDataService service, string text)
{
Logger.Trace(text);
}
Now I have no idea how to instantiate this class with MEF. I guess this is a quite common scenario so I wonder if MEF is not capable of handling this?