将新项目添加到解决方案中,作为重构的一部分

时间:2018-11-05 21:29:46

标签: visual-studio roslyn vsix

是否可以从CodeAction类向解决方案添加新项目?

上下文:

我有CodeRefactoringProvider生成了一些代码,我想将该代码放在新项目中。

我为此目的实现了CodeRefactoringProviderCodeAction,并尝试从我从CodeRefactoringContext得到的解决方案实例中添加项目,例如

 context.RegisterRefactoring(
            CodeAction.Create("Create New Project",
            (c)=>                
                Task.Run( 
                    ()=>
                    {
                        var proj = context.Document.Project.Solution.AddProject("NewProject", "NewProject", "C#");
                        return proj.Solution;
                    })           
            ));

这给了我

    System.AggregateException : One or more errors occurred. ---> Adding projects is not supported.
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout,CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.InvokeWorker(Func`1 getFromDocument,IProgressTracker progressTracker,CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedAction.<>c__DisplayClass18_0.<InvokeCore>b__0()
   at Microsoft.CodeAnalysis.Extensions.IExtensionManagerExtensions.PerformAction(IExtensionManager extensionManager,Object extension,Action action)
---> (Inner Exception #0) System.NotSupportedException : Adding projects is not supported.
   at Microsoft.CodeAnalysis.Workspace.CheckAllowedSolutionChanges(SolutionChanges solutionChanges)
   at Microsoft.CodeAnalysis.Workspace.TryApplyChanges(Solution newSolution,IProgressTracker progressTracker)
   at Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.VisualStudioWorkspaceImpl.TryApplyChanges(Solution newSolution,IProgressTracker progressTracker)
   at Microsoft.CodeAnalysis.CodeActions.ApplyChangesOperation.TryApply(Workspace workspace,IProgressTracker progressTracker,CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.Editor.Implementation.CodeActions.CodeActionEditHandlerService.ProcessOperations(Workspace workspace,ImmutableArray`1 operations,IProgressTracker progressTracker,CancellationToken cancellationToken)
   at async Microsoft.CodeAnalysis.Editor.Implementation.CodeActions.CodeActionEditHandlerService.ApplyAsync(<Unknown Parameters>)<---

我尝试使用IVsSolution服务添加项目,但出现错误:

 The operation could not be completed. A null reference pointer was passed to the stub. 

那么,如何在解决方案中创建一个新项目?

1 个答案:

答案 0 :(得分:0)

实际上,您需要操纵VS UI,而不是解决方案文件或其表示形式(context.Document)。否则,我希望您需要手动操作所有众所周知的“先保存更改”功能。什么是复杂的。

因此,您应该调用VS UI方法(表示COM):Solution2.AddFromFile(String, Boolean)

https://docs.microsoft.com/en-us/dotnet/api/envdte80.solution2.addfromfile?view=visualstudiosdk-2017#EnvDTE80_Solution2_AddFromFile_System_String_System_Boolean_

此调用将作为起作用,并且看起来符合您的预期。