简体   繁体   English

MEF 导入的属性始终为 null

[英]MEF Imported property is always null

In a minimal application I'm using to understand how MEF works I have the following class and interface,在我用来了解 MEF 工作原理的最小应用程序中,我有以下 class 和接口,

[Export(typeof(IAnimal))]
    public class Animal : IAnimal
    {
                public string Name { get; set; }
        public string GetAnimalName()
        {
            Name = "cat";
            return Name;
        }
    }
internal interface IAnimal
{
    string GetAnimalName();
}

In another Class Outside I'm trying to use MEF property injection to get an instant of the exported IAnimal as below,在另一个 Class 之外,我正在尝试使用 MEF 属性注入来获取导出的 IAnimal 的瞬间,如下所示,

[Import(typeof(IAnimal))]
public IAnimal AnimalProperty{ get; set; }

This property "AnimalProperty" is always null and I can't understand where the missing piece is.此属性“AnimalProperty”始终为 null,我不明白缺少的部分在哪里。 Any thoughts on what I might be missing here?关于我可能在这里遗漏的任何想法?

Without more context I cannot say for sure what the problem is but here are a few things that I can think of that may be what is happening:如果没有更多上下文,我无法确定问题出在哪里,但这里有一些我能想到的可能正在发生的事情:

  1. You are creating the instance of the outside class that is using the IAnimal property using the new() keyword, instead of telling Dependency Injection to inject it for you.您正在使用new()关键字创建使用 IAnimal 属性的外部 class 的实例,而不是告诉依赖注入为您注入它。 The Dependency Injection Container will NOT inject the dependencies needed for the class if the class itself was not created by the DI Container.如果 class 本身不是由 DI 容器创建的,则依赖项注入容器将不会注入 class 所需的依赖项。 If this is the case register your outside class in the DI Container and let it create it for you.如果是这种情况,请在 DI 容器中注册您的外部 class 并让它为您创建它。 If you are instantiating the outside class at the very beginning of your application (like in Main() for example) and you have a reference to CompositionContainer you can use var outsideClassInstance = compositionCointainer.GetExportedValue<OutsideClass>();如果您在应用程序的一开始就实例化外部 class(例如在 Main() 中)并且您有对CompositionContainer的引用,您可以使用var outsideClassInstance = compositionCointainer.GetExportedValue<OutsideClass>();
  2. You are checking the value of the IAnimal property in the constructor of its class.您正在检查其 class 的构造函数中的 IAnimal 属性的值。 The DI Container sets the values of the properties after the constructor has ran hence the property having the default value of null. DI 容器在构造函数运行后设置属性的值,因此该属性具有默认值 null。 Anything you add the [Import] attribute on will not be available in the constructor of its class.您添加 [Import] 属性的任何内容在其 class 的构造函数中都将不可用。

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

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