22
votes

I have the following method that should retrieve a list of loaded local (in bin folder) assemblies:

static IEnumerable<Assembly> GetLocalAssemblies()
    {
        Assembly callingAssembly = Assembly.GetCallingAssembly();
        string path = new Uri(Path.GetDirectoryName(callingAssembly.CodeBase)).AbsolutePath;

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        return assemblies.Where(x => !x.IsDynamic && new Uri(x.CodeBase).AbsolutePath.Contains(path)).ToList();
    }  

But, the list of assemblies is missing a couple assemblies that I need it to have. The assemblies I need are managed (c# .net 4), are referenced in the project, and are present in the bin folder.

Why are binaries that are present in the bin folder NOT swept into the AppDomain when the application starts?

3
out of curiosity, what is the value of string path?David Sulpy
It's the path to the bin folder for the project.Byron Sommardahl

3 Answers

41
votes

Adil has it, but in more detail:

The .NET CLR uses Just-In-Time compilation. Among other things, this means it loads assemblies on first use. So, despite assemblies being referenced by an assembly in use, if the references haven't yet been needed by the CLR to execute the program, they're not loaded and so will not appear in the list of assemblies in the current AppDomain.

Another thing which may or may not apply, is that if you have the same version of the assembly in the GAC, the CLR uses the GAC preferentially over local assemblies, UNLESS the path to those assemblies is specified in the DEVPATH environment variable. If this is the case and the CLR is using the GAC copy of any of the "missing" assemblies, they'll have differing CodeBase values and won't show up in your Linq query results.

One other thing: you may want to consider using the Location property instead of the CodeBase property. The Location property contains the absolute path to the assembly that was loaded at runtime. The CodeBase property is slightly different, and may not be the same for all assemblies in a full build of a project.

11
votes

The CurrentDomain.GetAssemblies() only return loaded assemblies not all assemblies which are available in execution folder.

This is what microsoft say about it "GetAssemblies method to get a list of all assemblies that have been loaded into the application domain." click here

5
votes

Try initiating any class in these missing assemblies and then run your code again.. The assemblies are loaded when needed only with the first call to anything related to that assembly.