简体   繁体   中英

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. 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 )

  • 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

NDepend lets write custom code rules through C# LINQ queries. Around 200 default code rules are provided. This LINQ syntax makes it straightforward to write the rule you are asking for:

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...).

NDepend can be integrated in VS 2012, 2010, 2008 and has facility to edit LINQ rules, and browse their results live. 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?

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