[英]How to fulfill System.Composition MEF ImportingConstructor with an instance
I'm using MEF (System.Composition from nuget) + Common.Logging and have classes that call ILog, eg, 我正在使用MEF(来自nuget的System.Composition)+ Common.Logging,并且具有调用ILog的类,例如,
[Export(typeof(ITranslator))]
public class ATranslator : BaseTranslator
{
[ImportingConstructor]
public ATranslator(ILog log)
{
...
}
The logger instance is available from Common.Logging via log = LogManager.GetLogger<ITranslator>();
记录器实例可从Common.Logging通过log = LogManager.GetLogger<ITranslator>();
but how do I plugin this into my composition container? 但是如何将其插入到合成容器中?
var container = new ContainerConfiguration()
.WithAssembly(typeof(ITranslator).Assembly)
.CreateContainer();
container.SatisfyImports(this);
so that I can 这样我就可以
[ImportMany]
private IEnumerable<ITranslator> Translators { get; set; }
without 没有
System.Composition.Hosting.CompositionFailedException : No export was found for the contract 'ILog' -> required by import 'log' of part 'ATranslator' -> required by import 'item' of part 'ITranslator[]' -> required by initial request for contract 'IEnumerable { IsImportMany = True }' System.Composition.Hosting.CompositionFailedException:未找到合同“ ILog”的导出->“ ATranslator”部分的导入“ log”所需的出口->“ ITranslator []”部分的导入“ item”所需的出口->合同初始请求“ IEnumerable {IsImportMany = True}”
Maybe you can try to do the export to ILog as a property in other class? 也许您可以尝试将ILog作为其他类的属性导出到ILog?
public class LogExporter
{
[Export(typeof(ILog))]
public ILog Log
{
return LogManager.GetLogger<ITranslator>();
}
}
Alternatively you can try to do it using ComposeExportedValue Method with code instead of attributes: 另外,您可以尝试使用带有代码而不是属性的ComposeExportedValue方法来执行此操作:
container.ComposeExportedValue<ILog>(LogManager.GetLogger<ITranslator>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.