Importing dependencies with MEF

Feb 4, 2011 at 1:20 PM

I don't know how to get my imports satisfied. I'm using the VS Templates for creating my project.

I'm exporting a property

    public class PythonEnv
    {
        [Export("CreatePythonEngine")]
        public Func<ScriptEngine> CreatePythonEngine = () =>
        {
            var engine = Python.CreateEngine();
            dynamic sys = engine.Runtime.GetSysModule();
            return engine;
        };
    }

but it isn't satisfied by the bootstrapper from my ShellViewModel

 

    [Export(typeof(IShell))]
    public class ShellViewModel : IShell 
    {
        [Import("CreatePythonEngine")]
        Func<ScriptEngine> createPythonEngine;

        public ShellViewModel()
        {
            var engine = createPythonEngine();
        }

    }

 

 

Any hints, what's wrong with my Import?

 

 

 

Coordinator
Feb 4, 2011 at 1:31 PM
Edited Feb 4, 2011 at 1:31 PM

One problem with the code that you show is that you are using field injection which MEF will do after the constructor runs. You should be able to solve this by making it a ctor dependency:

 

[ImportingConstructor]
public ShellViewModel([Import("CreatePythonEngine")]Func<ScriptEngine> engineFactory){
   ///do stuff
}