上一篇,我们打造了一个简单的分析器,但是我们实际使用分析器就是为了对项目做分析检测,增加一些非语法的自检的

比如Asp.Net Core 3.0的替换依赖注入检测

设计分析

我们创建一个默认的Asp.Net Core 3.0的项目

打开Startup.cs

大致结构如下

我们要针对Startup分析,第一方法ConfigureServices的返回类型必须是void

这是Asp.Net Core 3.0的改动之一,所以,当Startup.ConfigureServices返回类型不等于void的时候,我们就抛出错误提示

我们编写一个Startup的监视代码

    public class StartupAnalyzerContext : BaseAnalyzContext
{
private static DiagnosticDescriptor NotFindConfigureServices = new DiagnosticDescriptor("Class", "Startup", "未找到方法ConfigureServices", "Error", DiagnosticSeverity.Error, true);
public override DiagnosticDescriptor[] SupportedDiagnostics => new DiagnosticDescriptor[]
{
NotFindConfigureServices
}; public override void Execute(SyntaxNodeAnalysisContext context)
{
if (context.Node.Kind() == SyntaxKind.ClassDeclaration &&
context.Node is ClassDeclarationSyntax classDeclaration &&
classDeclaration.Identifier.Text.Equals("Startup")
)
{
var methods = classDeclaration.Members.OfType<MethodDeclarationSyntax>(); if (!methods.Any(_method => _method.Identifier.Text.Equals("ConfigureServices")))
context.ReportDiagnostic(Diagnostic.Create(NotFindConfigureServices, classDeclaration.GetLocation()));
else
{ }
}
}
}

  

如果没在Startup类里找到ConfigureServices方法则抛出错误

我们注释掉ConfigureServices方法

看看结果

已经可以正常分析方法了

下一步,我们分析ConfigureServices方法的返回值是否是void

                else
{
var voidSymbol = context.Compilation.GetTypeByMetadataName(typeof(void).FullName); var configureServices = methods.FirstOrDefault(_method => _method.Identifier.Text.Equals("ConfigureServices")); var returnType = configureServices.ReturnType;
var typeInfo = context.SemanticModel.GetTypeInfo(returnType); if (!typeInfo.Type.Equals(voidSymbol))
context.ReportDiagnostic(Diagnostic.Create(ConfigureServicesReturnType, configureServices.GetLocation()));
}

  

我们刚才的else部分逻辑,找到了ConfigureServices方法才进入这部分逻辑,我们修改一下ConfigureServices方法返回值,改为Asp.Net Core 3.0一下,常见的IServiceProvider

完善AspectCore的依赖注入替换分析

项目引用AspectCore.Extensions.DependencyInjection

判断Program.CreateHostBuilder是否存在

分析CreateHostBuilder的代码体,是否存在一个UseServiceProviderFactory方法,存在则判断是否是泛型AspectCore.Injector.IServiceContainer的类

    public class ProgramAnalyzerContext : BaseAnalyzContext
{
private static DiagnosticDescriptor NotFindCreateHostBuilder = new DiagnosticDescriptor("Class", "Program", "未找到方法CreateHostBuilder", "Error", DiagnosticSeverity.Error, true);
private static DiagnosticDescriptor CreateHostBuilderReturnType = new DiagnosticDescriptor("Class", "Program", "无法分析返回值类型非IHostBuilder的CreateHostBuilder方法", "Error", DiagnosticSeverity.Error, true);
private static DiagnosticDescriptor NotFindUseServiceProviderFactory = new DiagnosticDescriptor("Class", "Program", "未找到UseServiceProviderFactory方法", "Error", DiagnosticSeverity.Error, true);
private static DiagnosticDescriptor AspectCoreServiceProviderFactory = new DiagnosticDescriptor("Class", "Program", "请Nuget安装AspectCore.Extensions.DependencyInjection", "Error", DiagnosticSeverity.Error, true);
private static DiagnosticDescriptor UseServiceProviderFactoryType = new DiagnosticDescriptor("Class", "Program", "UseServiceProviderFactory(new AspectCoreServiceProviderFactory())", "Error", DiagnosticSeverity.Error, true); public override DiagnosticDescriptor[] SupportedDiagnostics => new DiagnosticDescriptor[]
{
NotFindCreateHostBuilder,
CreateHostBuilderReturnType,
NotFindUseServiceProviderFactory,
AspectCoreServiceProviderFactory,
UseServiceProviderFactoryType
}; public override void Execute(SyntaxNodeAnalysisContext context)
{
if (context.Node.Kind() == SyntaxKind.ClassDeclaration &&
context.Node is ClassDeclarationSyntax classDeclaration &&
classDeclaration.Identifier.Text.Equals("Program")
)
{
var methods = classDeclaration.Members.OfType<MethodDeclarationSyntax>(); if (!methods.Any(_method => _method.Identifier.Text.Equals("CreateHostBuilder")))
context.ReportDiagnostic(Diagnostic.Create(NotFindCreateHostBuilder, classDeclaration.GetLocation()));
else
{
var aspectCoreServiceProviderFactorySymbol = context.Compilation.GetTypeByMetadataName("AspectCore.Extensions.DependencyInjection.AspectCoreServiceProviderFactory");
var iServiceContainerSymbol = context.Compilation.GetTypeByMetadataName("AspectCore.Injector.IServiceContainer"); if (aspectCoreServiceProviderFactorySymbol == null)
{
context.ReportDiagnostic(Diagnostic.Create(AspectCoreServiceProviderFactory, classDeclaration.GetLocation())); return;
} var createHostBuilder = methods.FirstOrDefault(_method => _method.Identifier.Text.Equals("CreateHostBuilder")); var expressionBody = createHostBuilder.ExpressionBody as ArrowExpressionClauseSyntax; if (expressionBody != null)
{
var expressions = ConvertArrowExpression(expressionBody); if (!expressions.Any(expression=> ((MemberAccessExpressionSyntax)expression.Expression).Name.Identifier.Text.Equals("UseServiceProviderFactory")))
context.ReportDiagnostic(Diagnostic.Create(NotFindUseServiceProviderFactory, createHostBuilder.GetLocation()));
else
{
var useServiceProviderFactoryExpression = expressions.FirstOrDefault(expression => ((MemberAccessExpressionSyntax)expression.Expression).Name.Identifier.Text.Equals("UseServiceProviderFactory"));
var method = context.SemanticModel.GetSymbolInfo(useServiceProviderFactoryExpression.Expression).Symbol as IMethodSymbol; if (!method.TypeArguments.Any(_param => _param.Equals(iServiceContainerSymbol)))
context.ReportDiagnostic(Diagnostic.Create(UseServiceProviderFactoryType, createHostBuilder.GetLocation()));
}
}
}
}
} private List<InvocationExpressionSyntax> ConvertArrowExpression(ArrowExpressionClauseSyntax expresionBody)
{
var result = new List<InvocationExpressionSyntax>();
var firstExpresson = (InvocationExpressionSyntax) expresionBody.Expression;
var expression = firstExpresson; result.Add(expression); while (IsNext(expression))
{
expression = Next(expression);
result.Add(expression);
} return result;
} private InvocationExpressionSyntax Next(InvocationExpressionSyntax expression)
{
var method = (MemberAccessExpressionSyntax) expression.Expression; Console.WriteLine($"{method.Name}"); return (InvocationExpressionSyntax)method.Expression;
} private bool IsNext(InvocationExpressionSyntax expression)
{
var method = (MemberAccessExpressionSyntax)expression.Expression; return method.Expression.Kind() == SyntaxKind.InvocationExpression;
}
}

打造静态分析器(二)基于Asp.Net Core 3.0的AspectCore组件检测的更多相关文章

  1. 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(1)

    最近使用vscode比较多. 学习了一下如何在mac上使用vscode开发asp.netcore项目. 这里是我写的关于vscode的一篇文章: https://www.cnblogs.com/cgz ...

  2. [译]基于ASP.NET Core 3.0的ABP v0.21已发布

    基于ASP.NET Core 3.0的ABP v0.21已发布 在微软发布仅仅一个小时后, 基于ASP.NET Core 3.0的ABP v0.21也紧跟着发布了. v0.21没有新功能.它只是升级到 ...

  3. 基于ASP.NET Core 3.0快速搭建Razor Pages Web应用

    前言 虽然说学习新的开发框架是一项巨大的投资,但是作为一个开发人员,不断学习新的技术并快速上手是我们应该掌握的技能,甚至是一个.NET Framework开发人员,学习.NET Core 新框架可以更 ...

  4. 基于Asp.Net Core 5.0依赖Quartz.Net框架编写的任务调度web管理平台

    源码地址: https://github.com/246850/Calamus.TaskScheduler 演示地址:http://47.101.47.193:1063/ 1.Quartz.NET框架 ...

  5. 基于ASP.NET Core 6.0的整洁架构

    大家好,我是张飞洪,感谢您的阅读,我会不定期和你分享学习心得,希望我的文章能成为你成长路上的垫脚石,让我们一起精进. 本节将介绍基于ASP.NET Core的整洁架构的设计理念,同时基于理论落地的代码 ...

  6. 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(2)

    第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 为Domain Model添加约束 前一部分, 我们已经把数据库创建出来了. 那么我们先看看这个数据库 ...

  7. 基于ASP.NET Core 5.0使用RabbitMQ消息队列实现事件总线(EventBus)

    文章阅读请前先参考看一下 https://www.cnblogs.com/hudean/p/13858285.html 安装RabbitMQ消息队列软件与了解C#中如何使用RabbitMQ 和 htt ...

  8. 用VSCode开发一个基于asp.net core 2.0/sql server linux(docker)/ng5/bs4的项目(3)

    第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 由于 ...

  9. 如何基于asp.net core的Identity框架在mysql上作身份验证处理

    首先了解这个概念,我一开始也是理解和掌握基本的概念,再去做程序的开发.Identity框架是微软自己提供,基于.net core平台,可拓展.轻量 级.面向多个数据库的身份验证框架.IdentityS ...

随机推荐

  1. SQLserver , MySQL的区别和各自的一些简单方法案列

    SQL Server数据库和MySQL数据库有什么区别呢?今天我们来分析一下这两种数据库的不同之处以及这两种数据库的一些简单用途:SQL Server数据库和MySQL数据库有什么区别: 对于程序开发 ...

  2. 数据可视化之DAX篇(十七)Power BI表格总计行错误的终极解决方案

    https://zhuanlan.zhihu.com/p/68183990 我在知识星球收到的问题中,关于表格和矩阵(以下统称表格)总计行错误算是常见的问题之一了,不少初学者甚为不解,在Excel透视 ...

  3. python之爬虫(十一) 实例爬取上海高级人民法院网开庭公告数据

    通过前面的文章已经学习了基本的爬虫知识,通过这个例子进行一下练习,毕竟前面文章的知识点只是一个 一个单独的散知识点,需要通过实际的例子进行融合 分析网站 其实爬虫最重要的是前面的分析网站,只有对要爬取 ...

  4. How to install nginx in Ubuntu

    The steps for installing the nginx on Ubuntu below. 1.install the packages first. apt-get install gc ...

  5. C#各类集合介绍

    集合(Collection)类是专门用于数据存储和检索的类.这些类提供了对栈(stack).队列(queue).列表(list)和哈希表(hash table)的支持.大多数集合类实现了相同的接口. ...

  6. Python Ethical Hacking - VULNERABILITY SCANNER(5)

    EXPLOITATION - XSS VULNS XSS - CROSS SITE SCRIPTING VULNS Allow an attacker to inject javascript cod ...

  7. split().reverse().join()代码解析

    split() 方法用于把一个字符串分割成字符串数组. reverse() 方法用于颠倒数组中元素的顺序. join() 方法用于把数组中的所有元素放入一个字符串.

  8. select、poll和epoll之间的区别

    在深入理解select.poll和epoll之间的区别之前,首先要了解什么是IO多路复用模型. IO多路复用 简单来说,IO多路复用是指内核一旦发现进程指定的一个或者多个IO条件准备就绪,它就通知该进 ...

  9. 微信PC端多开的秘密

    微信电脑端也能多开 昨天,偶然从好朋友小林(微信公众号:小林Coding)处得知,他的电脑居然可以同时上两个微信号. 手机端多开微信我知道,像华为.小米等手机系统都对此做了支持,不过在运行Window ...

  10. Flutter防止布局溢出

    添加一层可滑动View(Widget)的布局, 将之前进行包裹: return new Scaffold(      appBar: new AppBar(        title: new Tex ...