Note that there are some explanatory texts on larger screens.

plurals
  1. POMEF+MVVM: How to instantiate a class with non-importing or mixed parameters
    text
    copied!<p>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:</p> <pre><code>// BarViewModel's constructor has one single string parameter IBarViewModel bar = container.GetExportedValue&lt;IBarViewModel&gt;("bar title"); </code></pre> <p>Obviously MEF wouldn't let me do this.</p> <p>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).</p> <p>So then I tried to use a ViewModelFactory to achieve this. I referenced this <a href="http://pglazkov.blogspot.com.au/2011/04/mvvm-with-mef-viewmodelfactory.html" rel="nofollow">article</a></p> <p>and came up something like this:</p> <pre><code>[Export(typeof(IBarViewModelFactory))] public class BarViewModelFactory : IBarViewModelFactory { [Import] public Lazy&lt;CompositionContainer&gt; 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; } </code></pre> <p>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.</p> <p>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.</p> <p>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:</p> <pre><code>[Import] public ILogger Logger {get;set;} [ImportingConstructor] public SomeClass(IDataService service, string text) { Logger.Trace(text); } </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload