How to test if certain assemblies have been loaded

2019-06-28 06:37发布

问题:

This question already has an answer here:

  • How do you loop through currently loaded assemblies? 2 answers

I have some code that uses the Crystal Reports runtime libraries to generate and discard a small dummy report, in order to ensure that the libraries are loaded into memory in good time before the user creates a genuine report. (It's a 'perceived performance' issue.) The performance has been notably improved when the user generates a report, so that clearly all works.

Now I need to write a unit test that proves that the Crystal libraries have indeed been loaded into memory when expected - however my attempts to test what is there using Assembly.GetExecutingAssembly().GetModules() does not help. (GetCallingAssembly().GetModules() is no better either.)

How can I check from within my unit test to see if these assemblies have been loaded?

TIA

回答1:

The following code example uses the GetAssemblies method to get a list of all assemblies that have been loaded into the application domain. The assemblies are then displayed to the console.

public static void Main() 
    {
        AppDomain currentDomain = AppDomain.CurrentDomain;
        //Provide the current application domain evidence for the assembly.
        Evidence asEvidence = currentDomain.Evidence;
        //Load the assembly from the application directory using a simple name. 

        //Create an assembly called CustomLibrary to run this sample.
        currentDomain.Load("CustomLibrary",asEvidence);

        //Make an array for the list of assemblies.
        Assembly[] assems = currentDomain.GetAssemblies();

        //List the assemblies in the current application domain.
        Console.WriteLine("List of assemblies loaded in current appdomain:");
            foreach (Assembly assem in assems)
                Console.WriteLine(assem.ToString());
    }

P.S. : To run this code example, you need to create an assembly named CustomLibrary.dll, or change the assembly name that is passed to the GetAssemblies method.

See here on MSDN



标签: c# .net dll