Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a correct way of forcing assembly load into current domain

Tags:

c#

.net

I have a project that uses several class libraries that are part of my project, first AssemblyA is loaded, then AssemblyB is loaded. In AssemblyA there is code that does the following

var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var assemblyB = assemblies
                .Where(x=>x.GetName() == "AssemblyB")
                .First();
var type = assemblyB.GetType("AssemblyB_Type");

Unfortunately when AssemblyA tries to do that, AssemblyB is not loaded yet into CurrentDomain, so to load that assembly I'm doing the following unnecessary thing:

var x = typeof(AssemblyB.AssemblyB_Type);

The compiler shows warning that this line is not needed, though I can't find words to explain it that otherwise it won't work, so the question would be, how do you correctly (in Feng Shui terms) force Assembly load into CurrentDomain without doing extra-unuseful plumbing

like image 858
Lu4 Avatar asked Dec 15 '11 21:12

Lu4


4 Answers

If your referenced assemblies are deployed correctly, they should "just load" if you call one of its types. The .NET framework should take care of this for you.

Here's a good article explaining the way the framework searches for your referenced assemblies: http://msdn.microsoft.com/en-us/library/yx7xezcf(v=vs.71).aspx

I'm curious what you're doing that you need to load an assembly prematurely like this?

A hack to answer your direct question is to use Assembly.Load(string location) - though I would discourage this unless absolutely necessary. http://msdn.microsoft.com/en-us/library/ky3942xh.aspx

like image 37
Dlongnecker Avatar answered Nov 05 '22 05:11

Dlongnecker


Your existing code is the best way to do that (AFAIK).

To get rid of the warning, change it to

typeof(AssemblyB.AssemblyB_Type).ToString();
like image 103
SLaks Avatar answered Nov 05 '22 03:11

SLaks


So, you could just load all the assemblies in your bin directory into the app domain. This should solve your problem.

var assemblies = Directory.GetFiles(containingDirectory, "*.dll")'

foreach (var assembly in assemblies)
{
    Assembly.Load(AssemblyName.GetAssemblyName(assembly));
}
like image 35
Craig Wilson Avatar answered Nov 05 '22 04:11

Craig Wilson


This is what I do:

public static class TypeExtensions {
   public static void EnsureAssemblyLoads(this Type pType) {
      // do nothing
   }
}

...

typeof(SomeType).EnsureAssemblyLoads();
like image 27
Dave Cousineau Avatar answered Nov 05 '22 03:11

Dave Cousineau