S3902 gives incorrect advice in class library projects


(Paul Hickman) #1


Rule 3902 says Assembly.GetExecutingAssembly should not be called and typeof(SomeTypeInThisAssembly) should be used to obtain a reference to the assembly.

Whilst this is a valid optimisation in a top-level assembly, in a class library, GetExecutingAssembly returns the top-level program or ASP.net web application assembly, whereas typeof(SomeTypeInThisAssembly) returns the assembly in which the statement appears.

Normally, a class library would not have any compile-time references to the top-level assembly of the program, so following this advice is liable to introduce bugs by returning a different assembly to the one required.

(Valeri Hristov) #2

Hi Paul, I agree that a developer could introduce bugs if he replaces Assembly.GetExecutingAssembly() with typeof(SomeType). If you see this problem from unit testing perspective, calling Assembly.GetExecutingAssembly() would also be difficult to test, because in this case it would be the test runner if I am not wrong, and the tests will be difficult to write at best. I would hide the executing assembly-dependent code behind an interface and then inject an implementation where needed. This way your class libraries will not be “polluted” by the knowledge of the executing application and they will be easy to test.

(Paul Hickman) #3

Yes, I agree this isn’t good code - I’m using Sonar to review legacy code that dates from before dependency injection became a populate technique. However, my point was the advice given on the page explaining S3902 gives the impression that the compliant code is equivalent to the non-compliant code, when it does something different.