简体   繁体   English

FxCop自定义代码分析:在另一个类中检查类引用

[英]FxCop Custom Code analysis: check class reference in another class

I am writing a custom code analysis check wherein I need to check that the Model class in ASP .NET MVC application does not have reference of the controller class. 我正在编写一个自定义代码分析检查,其中我需要检查ASP .NET MVC应用程序中的Model类是否没有控制器类的引用。 But I am unable to find anything relevant to the same as to how to check that my controller for reference of the model class. 但是我找不到与如何检查我的控制器以引用模型类相同的东西。

如果您使用访问者方法( http://binarycoder.net/fxcop/html/check_and_visit.html )创建规则,则可以覆盖VisitMemberBinding方法以验证是否正在访问控制器类型的任何成员(假设您拥有识别特定目标类型是否有资格作为控制器的方法)。

The tool NDepend for .NET developer is particularly suited to write this kind of static analysis checks ( Disclaimer: I belong to the team that develops NDepend ) 用于.NET开发人员的NDepend工具特别适合于编写这种静态分析检查( 免责声明:我属于开发NDepend的团队

  • I am writing a custom code analysis check wherein I need to check that the Model class in ASP .NET MVC application does not have reference of the controller class 我正在编写一个自定义代码分析检查,其中我需要检查ASP .NET MVC应用程序中的Model类是否没有控制器类的引用

NDepend lets write custom code rules through C# LINQ queries. NDepend允许通过C#LINQ查询编写自定义代码规则。 Around 200 default code rules are provided. 提供了大约200个默认代码规则 This LINQ syntax makes it straightforward to write the rule you are asking for: 通过这种LINQ语法,可以轻松编写所需的规则:

warnif count > 0
let modelClasses = Application.Namespaces.WithNameLike("Model").ChildTypes()
let controllerClasses = Application.Namespaces.WithNameLike("Controller").ChildTypes()

from modelClass in modelClasses.UsingAny(controllerClasses)
select new { modelClass, 
             controllerClassesUsed = modelClass.TypesUsed.Intersect(controllerClasses) 
}

Obviously it is easy to tweak this rule, maybe you'd like to define modelClasses or controllerClasses through a different way (derive from a certain class, implement a certain interface...). 显然,调整此规则很容易,也许您想通过其他方式(从特定类派生,实现特定接口...)来定义modelClassescontrollerClasses

NDepend can be integrated in VS 2012, 2010, 2008 and has facility to edit LINQ rules, and browse their results live. NDepend可以集成到VS 2012、2010、2008中,并且可以编辑LINQ规则并实时浏览其结果。 Rules checking can also be integrated into your build process, and rules violation ca be shown in a report . 规则检查也可以集成到您的构建过程中,并且可以在报告中显示违反规则

在此处输入图片说明

  • But I am unable to find anything relevant to the same as to how to check that my controller for reference of the model class. 但是我找不到与如何检查我的控制器以引用模型类相同的东西。

I am not sure to understand this requirement, do you mean that you want to write a rule to check that controller classes are indeed using model classes? 我不确定要了解此要求,是否意味着要编写一条规则来检查控制器类是否确实在使用模型类?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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