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:
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>();
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.