简体   繁体   English

子类中的MEF导入对象为NULL

[英]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. 通过手动更新Bar类,您将绕过MEF,因此无法满足导入要求,应让MEF负责更新类。

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. 尝试也导入Bar类的实例..这样,MEF将实例化该实例,并满足导入要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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