Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I force load a referenced assembly?

Tags:

c#

.net

I have a third-party library that requires an assembly A to be loaded when I call into their code. That assembly is typically installed in the GAC, so I have several options to load it:

  1. I can explicitly call Assembly.Load(). However that requires the full name which I don't feel comfortable to hard code in my program.
  2. I can explicitly call Assembly.LoadWithPartialName(). That is an obsolete API of course, and of course I don't feel comfortable to lose control in versioning.
  3. I can reference the assembly in my Visual Studio project file, so I always get the version I built against. However, that won't work unless I create a dummy object in that assembly. The C# compiler simply ignores it if I don't.
  4. Same problem if I call Assembly.GetReferencedAssemblies and force load the matched one. The C# compiler simply won't reference my assembly even if I put it in the references list.

Now what I'm doing is to call typeof(A.Foo).Assembly.GetName() and ignore the return value. Is there a better way to do it?

like image 669
Todd Li Avatar asked Jul 07 '11 00:07

Todd Li


People also ask

What is the method to load assembly given its file name and its path?

LoadFrom(String) Loads an assembly given its file name or path.

When assembly will load on AppDomain?

If an assembly is loaded into the same AppDomain, then the class can be instantiated in the usual way. But if an assembly is loaded into a different AppDomain then it can be instantiated using reflection. Another way is an interface.

Can not load file or assembly?

In summary if you get the "Could not load file or assembly error", this means that either your projects or their references were built with a reference to a specific version of an assembly which is missing from your bin directory or GAC.


1 Answers

Option 1, for me, would be to reference it in the VS project.

But if you want a more passive approach you can use the AppDomain.CurrentDomain.AssemblyResolve event handler. It executes when an assembly is needed that is not found in the AppDomain. The event args will tell you the Assembly that is being sought and you can go grab it at that point using Assembly.Load()

like image 66
Glenn Ferrie Avatar answered Sep 19 '22 17:09

Glenn Ferrie