0

I have some C# projects that should have some configurations in the project that references them. I'd like to write a Roslyn analyzer(DiagnosticAnalyzer) to check if those directly referenced projects are configured.

"directly referenced" means the project is referenced by <ProjectReference ...> in the .csproj file.

I found a property and thought it would be helpful: Compilation.ReferencedAssembly.

MS said it would get all "Assembly identities of all assemblies directly referenced by this compilation."

But it gives me all the referenced projects, including direct and transitive.

Am I using it wrongly?

WAKU
  • 290
  • 3
  • 17

2 Answers2

3

An analyzer can't see into the projects being referenced -- the compiler only sees the DLLs being fed in from other projects in the end.

Jason Malinowski
  • 18,148
  • 1
  • 38
  • 55
  • Thank you, Jason, I saw your another answer just after I published the question. But I still don't understand what the "directly" means in the doc. – WAKU Aug 16 '23 at 23:30
  • I think it just means "not transitively", i.e. if this is a Compilation for A.dll, and A.dll references B.dll, it'll say B.dll, even if B.dll itself references C.dll. – Jason Malinowski Aug 21 '23 at 15:49
1

As @Jason said, the compiler isn't aware of the "MSBuild project" 1 concept at all. It's just passed dll references. You can grab a binlog of your build and look into the Csc task which is what invokes the compiler.

The set of dll passed to the compiler is calculated by MSBuild magic stuff. This is what you see as Compilation.ReferencedAssemblyNames.

If you have never grabbed a binlog and looked at it, I encourage you to do so. It's a very important thing to know and helps a lot diagnosing complex build issues.

One important question is, why do you have a requirement that a ProjectReference must be present directly? What issues caused by not meeting this requirement for your case?

Anyway, what you want to achieve is probably not a use case of a DiagnosticAnalyzer. This is something more suitable for an MSBuild target I think. You need to figure out how to do it depending on your specific case.

1 There is Microsoft.CodeAnalysis.Project, but it's in Workspaces layer which you must not use in analyzers/generators, and I'm not even sure whether it can provide you with the needed information or not (I haven't personally used it that much). You can't use it in an analyzer anyway.

Youssef13
  • 3,836
  • 3
  • 24
  • 41