[英]MEF Imported property is always null
在我用来了解 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();
}
在另一个 Class 之外,我正在尝试使用 MEF 属性注入来获取导出的 IAnimal 的瞬间,如下所示,
[Import(typeof(IAnimal))]
public IAnimal AnimalProperty{ get; set; }
此属性“AnimalProperty”始终为 null,我不明白缺少的部分在哪里。 关于我可能在这里遗漏的任何想法?
如果没有更多上下文,我无法确定问题出在哪里,但这里有一些我能想到的可能正在发生的事情:
new()
关键字创建使用 IAnimal 属性的外部 class 的实例,而不是告诉依赖注入为您注入它。 如果 class 本身不是由 DI 容器创建的,则依赖项注入容器将不会注入 class 所需的依赖项。 如果是这种情况,请在 DI 容器中注册您的外部 class 并让它为您创建它。 如果您在应用程序的一开始就实例化外部 class(例如在 Main() 中)并且您有对CompositionContainer的引用,您可以使用var outsideClassInstance = compositionCointainer.GetExportedValue<OutsideClass>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.