简体   繁体   中英

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,

[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,

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

This property "AnimalProperty" is always null and I can't understand where the missing piece is. 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. The Dependency Injection Container will NOT inject the dependencies needed for the class if the class itself was not created by the DI Container. If this is the case register your outside class in the DI Container and let it create it for you. 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>();
  2. You are checking the value of the IAnimal property in the constructor of its class. The DI Container sets the values of the properties after the constructor has ran hence the property having the default value of null. Anything you add the [Import] attribute on will not be available in the constructor of its class.

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