MEF import object in child class is NULL

414 views Asked by At

I'm facing a strange issue where an object can be imported just fine in a class. If I create an instance of another class from the first class, then try to import the same object in the child class, the import always fails!

First class:

public class Foo {

    [Import]
    private SomeExportedType foobar;

    public Foo() {
        foobar.Test(); // Works just fine

        Bar bar = new Bar();
        bar.Test();
    }
}

Second class:

public class Bar {

    [Import]
    private SomeExportedType foobar;

    public void Test() {
        foobar.Test(); // This fails because foobar is NULL
    }
}

All of this is pseudo code, or course, but it correctly reflects how my code is built. Why does the import in the child class fail?

1

There are 1 answers

2
BenjaminPaul On BEST ANSWER

By newing up your Bar class manually you are bypassing MEF and therefore the imports are not being satisfied, you should allow MEF to be in charge of newing up classes.

public class Foo {

    [Import]
    private SomeExportedType foobar;

    [Import]
    private Bar bar;

    public Foo() {
        foobar.Test(); // Works just 

        bar.Test(); // Should also work fine.
    }
}

Try importing an instance of your Bar class as well.. that way it will be instantiated by MEF and the imports satisfied.