简体   繁体   中英

AppDomain Creation : Resolving “Could not load file or assembly” error

This is just weird. Here's the code :

 AppDomain newDomain = AppDomain.CreateDomain("newDomain ", null,
            new AppDomainSetup
            {
                ApplicationBase = @"D:\myDLLFolderFullPath\"
            });

 Assembly a = newDomain.Load("myAssembly");

This throws the "Could not load file or assembly" error.
I checked my Assembly's dll is located under the specified folder path, and the name of the Assembly is correct.

When I copy myAssembly.dll into the CurrentDomain's main folder, it works !
It behaves as if the ApplicationBase setting for the new AppDomain has absolutely no effect and keep pointing to the Current AppDomain's AppBase.

Any Ideas ?

I am not sure if .NET allows loading assemblies from paths that are not relative to the main executable path.

So, I think that this is not allowed:

 D:\myExeFolderFullPath\main.exe
 D:\myDLLFolderFullPath\Mydll.dll

...while this should work:

 D:\myExeFolderFullPath\main.exe
 D:\myExeFolderFullPath\myDLLFolderFullPath\Mydll.dll

Update:

I had a similar problem with paths when working on the mygeneration project. The only way I found to get it running was to reorganize the folder structure I described in this answer.

See msdn for appDomain.load() method: *

This method should be used only to load an assembly into the current application domain.

  • This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap . If a version of the requested assembly is already loaded, this method returns the loaded assembly, even if a different version is requested.

I don't know what you want to do exactly...

But to load a dll into an AppDomain and create an instance, you can do it like this:

Create a AppDomain. Setup and security info are optional parameters.

 var appDomain = AppDomain.CreateDomain("A friendly name to identify your application", null, null);

Load your assembly:

   var assemblyName = AssemblyName.GetAssemblyName(@"C:\PathToYourApp\ConsoleApplication1.exe"));

Create an instance inside the app domain:

var instance = (Program)appDomain.CreateInstanceAndUnwrap(assemblyName.Name, "ConsoleApplication1.Program");

Important: The class you want to unwrap and access outside of you app domain, had to be marked with the [Serializable] Attrbute!

[Serializable]
class Program{}

Use the event appDomain.UnhandledException for exception handling outside the AppDomain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM