Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with AppDomain.CreateInstanceFromAndUnwrap

Tags:

c#

reflection

I'm using AppDomain.CreateInstanceFromAndUnwrap() to create an object in a different AppDomain. I couldn't get it to work because it kept throwing the following error at me:

Could not load file or assembly 'COMon, Version=2.0.4960.27874, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The module was expected to contain an assembly manifest.

However, I found that it is because it tries to load my DLL (which has the same name as my .NET assembly).

This is how I call the method:

_script = (Script)_appDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, "COMon.Scripting.Script");

It works fine as long as there isn't a native DLL file with the same name as my .NET assembly. Why does this happen when I'm passing it the full path and filename of my .NET assembly?

like image 953
mnoergaard Avatar asked Jul 31 '13 14:07

mnoergaard


1 Answers

when I'm passing it the full path and filename of my .NET assembly?

That's not how the method works. The first argument is the display name of the assembly. It is not a file name. The MSDN article recommends that you take a look at Assembly.FullName to learn more about display names.

So the normal CLR search rules will be in effect for finding the assembly. It will look in the GAC first, then in the probing path for the AppDomain. With a quirk that you didn't count on, the CLR does not pay attention to the filename extension for a file. The display name for an assembly doesn't specify it. So it considers an EXE and a DLL equivalent. Something you can see back in the trace for Fuslogvw.exe, the utility you always want to use when you have trouble like this. And in other places, adding a reference to an EXE works fine for example.

So it finds COMon.exe and that's a kaboom, it is not a managed assembly.

It isn't that clear what the proper workaround might be in your case, other than simply renaming the assembly. When you tinker with AppDomains then you typically also want to use AppDomainSetup and set the ApplicationBase or PrivateBinPath property.

like image 184
Hans Passant Avatar answered Oct 17 '22 23:10

Hans Passant