How do I get the namespaces of an assembly and not its dependencies?

Viewed 149

How do I get the namespaces of an assembly and not of its dependencies?

For example, if I get the namespaces using

assembly.GetTypes().Select(t => t.Namespace).Where(n => n != null).Distinct() 

would I not get the namespaces of the dependencies of that assembly as well?

How do I distinguish between the 2?

I am loading the assembly via Assembly.LoadFrom(path) and I understand that it automatically loads the assembly's dependencies. For the solution, do I have to load the assembly in a way that the dependencies are not loaded? If yes, how do I do that?

Also, I do not have any control over the Assembly creation, like adding an empty class etc.

EDIT: correcting an example

3 Answers

System.Linq.Expressions is in fact in the EntityFramework.dll.

Specifically, the following classes are in that DLL, under that namespace:

  • System.Linq.Expressions.EntityExpressionVisitor
  • System.Linq.Expressions.Internal.Error
  • System.Linq.Expressions.Internal.ReadOnlyCollectionExtensions

Also, you should also be seeing System.ComponentModel.DataAnnotations because EntityFramework.dll defines the class System.ComponentModel.DataAnnotations.Schema.IndexAttribute.

** Note, I am inspecting EntityFramework 6.0.0.0

To more directly answer your questions:

How do I get the namespaces of an assembly and not of its dependencies?

assembly.GetTypes().Select(t => t.Namespace)

Would I not get the namespaces of the dependencies of that assembly as well?

No.

How do I distinguish between the 2?

N/A

For the solution, do I have to load the assembly in a way that the dependencies are not loaded?

No.

If yes, how do I do that?

N/A

Assembly.LoadFrom() does not load the assembly's dependencies, so your code as it is will do exactly what you want.

Now, let's pretend it does load dependencies; again: it does not.

Assuming you somehow got all of the types in all of the loaded assemblies (a highly contrived situation), you could select only the types in the target assembly, and then apply your "distinct code."

types
    .Where(x => x.GetName().Name == "Your.Assembly.Name")
    .Select(t => t.Namespace)
    .Where(n => n != null)
    .Distinct()

Loading an assembly does "load" all dependent assemblies into memory, but the Assembly object you're dealing with only pertains to the assembly that you're explicitly loading, so calling GetTypes only loads the types defined in that assembly.

So if you're getting namespaces you don't expect, it's because there are types in that assembly in the namespace (types in a namespace don't all have to be contained in one assembly)

Related