VSIX扩展中使用EnvDTE为多项目模板添加共享项目引用的问题
问题原因
你遇到的报错本质是因为Shared共享项目(.shproj)和普通类库项目的引用逻辑完全不同,VSProject.References下的Add、AddProject方法仅支持添加常规类库项目、程序集、COM组件类的引用,无法识别共享项目的引用规则。
解决方案
有两种可行的实现方式,推荐优先使用第一种官方接口方案:
方案1:使用IVsSharedProjectReferenceManager接口添加
这是Visual Studio官方提供的专门用于处理共享项目引用的接口,兼容性最好,无需手动修改项目文件:
- 首先在你的VSIX项目中添加对
Microsoft.VisualStudio.Shell.Interop.12.0及以上版本程序集的引用 - 修改你的代码如下:
using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; // 原有获取sharedProj、version项目的逻辑不变 foreach (Project version in versionProjs) { VSProject vsProj = (VSProject)version.Object; if (sharedProj != null) { ThreadHelper.ThrowIfNotOnUIThread(); // 获取共享项目引用管理器实例 var sharedRefManager = ServiceProvider.GlobalProvider.GetService(typeof(SVsSharedProjectReferenceManager)) as IVsSharedProjectReferenceManager; if (sharedRefManager != null) { // 传入目标项目、共享项目类型、.shproj文件路径 sharedRefManager.AddSharedProjectReference(version, sharedProj.Kind, sharedProj.FileName); } } // 添加Resources项目引用的原有逻辑不变 if (resourceProj != null) { vsProj.References.AddProject(resourceProj); } }
方案2:手动修改项目文件XML
如果不想额外引用VS交互程序集,可以直接操作目标项目的.csproj文件,写入共享项目的导入节点:
ThreadHelper.ThrowIfNotOnUIThread(); // 获取目标项目的.csproj文件路径 string projPath = version.FileName; // 计算共享项目.projitems和.shproj的相对路径 string sharedProjDir = Path.GetDirectoryName(sharedProj.FileName); string targetProjDir = Path.GetDirectoryName(projPath); string relativeProjItemsPath = Path.GetRelativePath(targetProjDir, Path.Combine(sharedProjDir, sharedProj.Name + ".projitems")).Replace("\\", "\\\\"); string relativeShprojPath = Path.GetRelativePath(targetProjDir, sharedProj.FileName).Replace("\\", "\\\\"); // 加载项目XML XDocument projXml = XDocument.Load(projPath); XNamespace ns = projXml.Root.Name.Namespace; // 添加导入节点 projXml.Root.Add( new XElement(ns + "Import", new XAttribute("Project", relativeProjItemsPath), new XAttribute("Label", "Shared")), new XElement(ns + "Import", new XAttribute("Project", relativeShprojPath), new XAttribute("Condition", $"Exists('{relativeShprojPath}')"), new XAttribute("Label", "Shared")) ); // 保存并重载项目 projXml.Save(projPath); version.Reload();
注意事项
- 所有操作必须在UI线程执行,你代码中已有的
ThrowIfNotOnUIThread校验无需删除 - 确保执行添加逻辑前,解决方案内所有项目已经完成加载,避免路径识别错误
- 优先使用相对路径存储引用,避免解决方案迁移后引用失效
内容的提问来源于stack exchange,提问作者Leetheus
相关产品推荐
相关产品推荐

