Visual Studio vsix 项目 (MEF) 中的组件导入为空

Visual Studio component import is null in vsix project (MEF)

我正在编写 Visual Studio 扩展,我需要创建自己的 IWpfTextViewHost (CodeEditor Window)。这可以通过 ITextEditorFactoryService 完成,但必须通过 MEF 框架加载。

但我的导入总是 null,但我似乎无法弄清楚为什么我的导入是 null。我对 MEF 的工作原理有一个粗略的了解,有没有一种方法可以调用 Visual Studio 本身的 CompositionContainer?还是vsix项目构建这个容器?如果是,基于什么设置?

public class MyViewHost {

   [Import]
   public ITextEditorFactoryService TextEditorFactory { get; set; }

   public IWpfTextViewHost CreateViewHost(ITextBuffer textBuffer) 
   {
      var textView = this.TextEditorFactory.CreateTextView(textBuffer);
      return this.TextEditorFactory.CreateTextViewHost(textView, true);
   }

}

编辑 这是 extension.vsixmanifest

的相关部分
  <Assets>
      <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="Build%CurrentProject%" Path="|dllName;PkgdefProjectOutputGroup|" />
      <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" Path="dllName" />
  </Assets>

我根据@nejcs 的回复和这个 gist 找到了答案。 我会 post 解决方案:

[Export(typeof(IMyViewHost))]
public class MyViewHost : IMyViewHost
{
    [Import]
    public ITextEditorFactoryService TextEditorFactory { get; set; }

    public IWpfTextViewHost CreateViewHost(ITextBuffer textBuffer)
    {
        var textView = this.TextEditorFactory.CreateTextView(textBuffer);
        return this.TextEditorFactory.CreateTextViewHost(textView, true);
    }

IMyViewHostCreateViewHost 方法的接口。 SatisfyImportsOnce 必须在扩展命令 class 的构造函数中调用,并且 IMyViewHost 必须在此扩展命令 class.

中导入