First wrong point in the I can see in your code is this:
if (t.GetInterfaces().Contains(typeof(IHeaderBarComponent))) ...
Is your purpose selecting the type which implements
IHeaderBarComponent
?
This is how it's done:
System.Type headerBarComponentType = typeof(IHeaderBarComponent);
if (headerBarComponentType.IsAssignableFrom(t)) { }
If some type
t
implements
IHeaderBarComponent
, some object with the compile-time type of this interface can be assignable from an instance of
t
, then and only then. Obviously, isn't it?
Also, you should avoid getting anything by name. This is absolutely not needed. Actually, defining an interface is probably the best method of identification and filtering of the classes/structures instantiated through Reflection. The interface type is the identity object by itself, and run-time system (CLR) takes care of its uniqueness.
Now, your consideration about loading assemblies in not clear or incorrect. If assemblies are formally referenced, they might be loaded by the time you execute your Reflection code, but it they are not, you need to load them first. But you mention "unreferenced assemblies" in the title of the question. You need to load them.
Now, this is one important fact that is not clearly explained in Microsoft documentation, or, probably, not explained at all. You can get a collection of assemblies in two different ways. First is your
AppDomain.CurrentDomain.GetAssemblies()
. The second approach is using
System.Reflection.Assembly.GetReferencedAssemblies
,
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getreferencedassemblies.aspx[
^].
With second approach, you can take some assembly (for example, your entry assembly, but it can be anything), get its reference assemblies and continue collecting assemblies recursively. In this way, you can collect all assemblies some given assembly depends on (or potentially may depend).
Now, if you compare the results (not considering assemblies loaded during run time, which is the obvious factor you can always take into account; for simplicity of explanation, let's say you don't load any), you will see, that in general case the results are different. The enumeration of assemblies
System.AppDomain.GetAssemblies
"optimizes out" the assemblies which are formally referenced but not actually used. The other method enumerates them
all.
You should choose one or another method depending on what you really need.
—SA