Roslyn CodeFix:创建文档

时间:2017-11-14 08:27:04

标签: c# roslyn roslyn-code-analysis codefixprovider

我正在玩Roslyn分析器和Codefixes。在我的场景中,我不希望每个域类都应该在另一个项目中有一个相应的构建器。

诊断部分没有问题,但现在我在使用codefix。 这就是我到目前为止所做的:

注册码(工作)

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) {
        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        var diagnostic = context.Diagnostics.First();
        var diagnosticSpan = diagnostic.Location.SourceSpan;

        // Find the type declaration identified by the diagnostic.
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().First();

        var equivalenceKey = "CreateTestDataBuilder";
        var codeAction = CodeAction.Create(equivalenceKey, c => CreateTestDataBuilderAsync(context.Document, declaration, c), equivalenceKey: equivalenceKey);
        context.RegisterCodeFix(codeAction, diagnostic);    
}

创建文档的代码(崩溃)

private async Task<Solution> CreateTestDataBuilderAsync(Document contextDocument, TypeDeclarationSyntax declaration, CancellationToken cancellationToken) {
        Project contextDocumentProject = contextDocument.Project;
        Solution solution = contextDocumentProject.Solution;
        Project testProject = solution.Projects.FirstOrDefault(p => p.Name == contextDocument.Project.Name + ".Test");
        if (testProject == null) {
            return solution;
        }

        var semanticModel = await contextDocument.GetSemanticModelAsync(cancellationToken);
        var typeSymbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);

        string[] folders = new[] { "src/Builders" };
        Document testDataBuilderDocument = testProject.AddDocument(typeSymbol + "Builder.cs", SourceText.From(string.Format(TestDataBuilderTemplate, typeSymbol.Name)), folders);

        bool result = solution.Workspace.TryApplyChanges(solution);

        return solution;
}

我想我不知道如何使用codefixes来操作解决方案。有帮助吗?

0 个答案:

没有答案
相关问题