Я пытаюсь загрузить файл DLL в отдельный домен приложения, вызвать метод в файле DLL и получить от него ответ.Файл DLL не существовал в папке проекта bin
, при запуске приложения файл DLL загружался из другой папки.После завершения работы с файлом DLL я хочу выгрузить только что созданный домен приложения.
Шаги:
- Создание нового домена приложения
- Загрузите мою DLL, которую я хочу, в домен приложения
- Вызовите метод и получите ответ
- Выгрузите домен приложения
Вот то, что я пробовал до сих пор
Это код в MyAssembly.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace MyAssembly
{
public class MyClass
{
public static string MyMethod()
{
return "Hello there, this is message from MyAssembly";
}
}
}
Вот как я загружаю файл DLL
using System.Diagnostic;
using System.IO;
private class ProxyClass : MarshalByRefObject
{
public void LoadAssembly()
{
AppDomain dom;
string domainName = "new:" + Guid.NewGuid();
try
{
//Create the app domain
dom = AppDomain.CreateDomain(domainName, null, new AppDomainSetup
{
PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"),
ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName,
ShadowCopyFiles = "true",
ShadowCopyDirectories = "true",
LoaderOptimization = LoaderOptimization.SingleDomain,
});
string dllPath = @"C:\MyProject\MyAssembly.dll";//the path to my assembly file I want to load
//load the assembly to the new app domain
Assembly asm = dom.Load(File.ReadAllBytes(dllPath));//Error occurred at here
Type baseClass = asm.GetType("MyAssembly.MyClass");
MethodInfo targetMethod = baseClass.GetMethod("MyMethod");
string result = targetMethod.Invoke(null, new object[]{});
/*Do something to the result*/
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.ToString());
}
finally
{
//Finally unload the app domain
if (dom != null) AppDomain.Unload(dom);
}
}
}
public void BeginLoadDll()
{
ProxyClass proxy = new ProxyClass();
proxy.LoadAssembly();
//OR like this, which gave me same error message as well
//var dom = AppDomain.CreateDomain("new:" + Guid.NewGuid(), null, new AppDomainSetup
// {
// PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"),
// ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
// ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
// ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName,
// ShadowCopyFiles = "true",
// ShadowCopyDirectories = "true",
// LoaderOptimization = LoaderOptimization.SingleDomain,
// });
//ProxyClass proxy = (ProxyClass)dom.CreateInstanceAndUnwrap(
// typeof(ProxyClass).Assembly.FullName, typeof(ProxyClass).FullName);
//pr.LoadAssembly(watcherData, filePath);
}
Вот то, что я наблюдал до сих пор, яЯ не уверен, что это только у меня, или я что-то упустил
-Если «MyAssembly.dll» существует в папке проекта bin до запуска приложения, я могу загрузить файл DLL
-Если «MyAssembly.dll» не существовало в папке bin проекта до запуска приложения, вместо этого он был загружен в другое место, кроме папки bin проекта, я не могу загрузить файл dll.Например, папка bin проекта - «C: \ Main \ MyMainProject \ MyMainProject \ bin», а DLL загружается из C: \ MyProject \ MyAssembly.dll »
-Если я переместил« MyAssembly.dll »"файл в папку bin (используя File.Copy()
или File.Move()
), он каким-то образом останавливает выполнение остального кода.
Полученное сообщение об ошибке
Could not load file or assembly 'MyAssembly, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=2c20c56a5e1f4bd4' or one of its dependencies.
The system cannot find the file specified.
EDIT
Я знаю, что могу использовать Assembly.LoadFrom(@"PATH\TO\MY\DLL")
, но проблема с этим в том, что я не могу выгрузить DLL