Extending Depender with your own custom dependency rules
In the previous post I introduced Depender, to help find dependency issues in your code (usually for testing).
I've added extensibility to it so that you can write your own rules. If you download depender there will also be a "src" directory in the zip file, which shows how the current rules it uses were built.
it should be really easy to created your own rules. Just :
- create your own assembly that has a name ending with ".Rules.dll"
- Implement IRule in your class, or, if you want to parse the contents of a method, inherit from MethodParserRule.
your rule will be automatically loaded according to the assembly naming convention and its interface.
here's how a simple rule looks:
public class FindOverridableMethodsRule:IRule
{
public void Check(MethodInfo info, Dependency parent)
{
if (!info.IsFinal && (info.IsVirtual || info.IsAbstract))
{
parent.Add(new Dependency(string.Format(" {0}() can be overriden", info.Name)));
}
}
public bool CanCheck(object obj)
{
return obj is MethodInfo;
}
public void Check(object obj, Dependency parent)
{
Check(obj as MethodInfo, parent);
}
}
and here's a rule that parses the contents of a method:
public class FindStaticMethodCallRule : MethodParserRule
{
protected override void DoChecks(MethodBase mehodBeingChecked, MethodBodyInfo methodBody, Dependency parent)
{
foreach (ILInstruction instruction in methodBody.Instructions)
{
if (instruction is InlineMethodInstruction)
{
InlineMethodInstruction line = instruction as InlineMethodInstruction;
if (line.Method.IsStatic)
{
string message =
string.Format("Static method call {0} on {1}", line.Method.Name,
line.Method.ReflectedType.Name);
parent.Add(new ProblemDependency(message));
}
}
}
}
}