Create a class that has an async method which uses another class:
namespace SomeNamespace
{
public class ClassWithAsyncMethod
{
public async void MethodAsync()
{
var otherClass = new OtherClass();
}
}
public class OtherClass
{
}
}
Create a rule that verifies that ClassWithAsyncMethod does not depend on OtherClass:
[Fact]
public void Class_should_not_depend_on_other_class()
{
var rule = Types().That().Are(typeof(ClassWithAsyncMethod)).
Should().NotDependOnAny(Types().That().Are(typeof(OtherClass)));
rule.Check(Architecture);
}
Expected result
Rule fails.
Actual result
Rule passes.
Reason
When using the async keyword the compiler creates a nested helper class that contains the logic of MethodAsync (the instantiation of OtherClass). MethodAsync itself contains just the logic to use the helper class. The analysis scans MethodAsync but not the nested helper class. So the dependency to OtherClass is not detected.
Solution
Extend analysis to scan the nested helper class also.
Background
Create a class that has an async method which uses another class:
Create a rule that verifies that ClassWithAsyncMethod does not depend on OtherClass:
Expected result
Rule fails.
Actual result
Rule passes.
Reason
When using the async keyword the compiler creates a nested helper class that contains the logic of MethodAsync (the instantiation of OtherClass). MethodAsync itself contains just the logic to use the helper class. The analysis scans MethodAsync but not the nested helper class. So the dependency to OtherClass is not detected.
Solution
Extend analysis to scan the nested helper class also.