我正在编写Visual Studio扩展,我需要创建自己的IWpfTextViewHost
(CodeEditor窗口)。这可以通过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的答案。我会发布解决方案:
[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);
}
IMyViewHost
是CreateViewHost
方法的接口。必须在扩展命令类的构造函数中调用SatisfyImportsOnce
,并且必须在此扩展命令类中导入IMyViewHost
。