简体   繁体   中英

MEF import object in child class is NULL

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM