简体   繁体   中英

How to add a using directive outside a namespace using Roslyn?

I have a CSharpSyntaxRewriter that adds a new using directive to my file:-

public class AddUsingDirective : CSharpSyntaxRewriter
{
    public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
    {
        // this adds the using directive inside the namespace not outside
        node = node.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyCompany.MyProject.DataAccessLayer.Abstractions"))).NormalizeWhitespace();

        return base.VisitNamespaceDeclaration(node);
    }
}

The problem is that is adds the new using directive inside the namespace but I want to add it to the other existing namespaces above the namespace declaration. Any ideas how I can do this?

public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
    // this adds the using directive inside the namespace not outside
    node = node.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("MyCompany.MyProject.DataAccessLayer.Abstractions"))).NormalizeWhitespace();

    return base.VisitNamespaceDeclaration(node);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM