Brondahl
Brondahl

Reputation: 8577

Is `GetReferencedAssemblies` a subset of `AppDomain.CurrentDomain.GetAssemblies()`?

I want to test some reflection code I've written.

There's an edge case that would occur if the ReferencedAssemblies were ever not already loaded into the AppDomain, i.e. if the following expression ever returned true:

typeof(MyType).Assembly.GetReferencedAssemblies()
    .Except(AppDomain.CurrentDomain.GetAssemblies().Select(assem => assem.GetName()))
    .Any()

I have 2 questions:

  1. Can that ever return true? (I think "yes" [and hence the answer to the headline question is "no"], though I'm not certain).
  2. Assuming it can ... then how can I orchestrate that, for the purposes of a unit test?

Upvotes: 0

Views: 241

Answers (1)

Brondahl
Brondahl

Reputation: 8577

As I suspected, it is NOT a subset.

You CAN have a situation in which a ReferencedAssembly has not currently been loaded into the AppDomain.CurrentDomain.

To achieve this in a test:

  1. Create a secondary csproj. (ProjTwo)
  2. Create a csproj-level dependency between your Test project and ProjTwo.
  3. Add an unused class that references some code in ProjTwo.
    • If necessary add a static class with a static no-op method to ProjTwo, and a second static class which just invokes that method to your Test proj.
  4. Do NOT reference ProjTwo assembly anywhere in your TestFixtures.

Voila!


Step 4. appears to mean that ProjTwo does not get Loaded, whilst Step 3. ensures that the compiler can't remove the reference so it still turns up in GetReferencedAssemblies(), dodging this problem.

Upvotes: 1

Related Questions