lundi 10 avril 2017

How to make .NET Reflection enumerate a class that is never actively used

Let us have a simple class library (ClassLibrary1)

namespace ClassLibrary1
{
    // a simple class

    public class Class1
    {

        // some methods...

        public void foo() { }

        public void bar() { }
    }
}

and a simple console application that keeps a reference to the library:

using System;

namespace ConsoleApplication1
{    
    class Program
    {
        static void Main(string[] args)
        {  
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var assembly in assemblies) Console.WriteLine(assembly.FullName.Split(' ')[0]);

        }
    }
}

When run, ConsoleAppliacation1 produces the following output:

mscorlib,
Microsoft.VisualStudio.HostingProcess.Utilities,
System.Windows.Forms,
System,
System.Drawing,
Microsoft.VisualStudio.HostingProcess.Utilities.Sync,
Microsoft.VisualStudio.Debugger.Runtime,
vshost32,
System.Core,
System.Xml.Linq,
System.Data.DataSetExtensions,
Microsoft.CSharp,
System.Data,
System.Net.Http,
System.Xml,
mscorlib.resources,
ConsoleApplication1,

As you can see, there is no ClassLibrary1 entry in the assemblies... but if I modify the ConsoleApplication1 to look like this (note the additional line declaring var x):

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // let us know about the assembly...
            var x = new ClassLibrary1.Class1();

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var assembly in assemblies) Console.WriteLine(assembly.FullName.Split(' ')[0]);       
        }
    }
}

then it does appear (see last line)...

mscorlib,
Microsoft.VisualStudio.HostingProcess.Utilities,
System.Windows.Forms,
System,
System.Drawing,
Microsoft.VisualStudio.HostingProcess.Utilities.Sync,
Microsoft.VisualStudio.Debugger.Runtime,
vshost32,
System.Core,
System.Xml.Linq,
System.Data.DataSetExtensions,
Microsoft.CSharp,
System.Data,
System.Net.Http,
System.Xml,
mscorlib.resources,
ConsoleApplication1,
ClassLibrary1,

This is a problem for me, because I actually need to enumerate all assemblies, even those that are never directly used, in order to automatically populate a list of classes defined in ClassLibrary1 via reflection.

either my google-fu isn't working, or my question isn't trivial...

Thank you in advance.





Aucun commentaire:

Enregistrer un commentaire