C# 如何在AppDomain下创建类的新实例

C# 如何在AppDomain下创建类的新实例,c#,reflection,dll,appdomain,C#,Reflection,Dll,Appdomain,我试图调用一个类在一个单独的AppDomain下运行,但遇到一个异常,即无法加载该类或其依赖项。这是我正在做的一个例子 AppDomain ad = AppDomain.CreateDomain("New domain"); IIdentity identity = new GenericIdentity("NewUser"); IPrincipal principal = new GenericPrincipal(identity, null); ad.SetThreadPrincipal(p

我试图调用一个类在一个单独的AppDomain下运行,但遇到一个异常,即无法加载该类或其依赖项。这是我正在做的一个例子

AppDomain ad = AppDomain.CreateDomain("New domain");
IIdentity identity = new GenericIdentity("NewUser");
IPrincipal principal = new GenericPrincipal(identity, null);
ad.SetThreadPrincipal(principal);
TestClass remoteWorker = (TestClass)ad.CreateInstanceAndUnwrap(
                         binFolder+"\\TestProject.dll",
                         "TestClass");
remoteWorker.Run(data1,data2);
在单独的TestProject中,我有一个名为TestClass的类:

 public class TestClass : MarshalByRefObject
 {
      public void Run(string name, string path)
      {
           //Some stuff
      }
  }
我已经检查了所有的路径,它们都是正确的。我得到一个错误:

Could not load file or assembly 'K:\\Installer\\Bin\\TestProject.dll' 
or one of its dependencies. The given assembly name or codebase was invalid. 
(Exception from HRESULT: 0x80131047)

我尝试更改路径,将其移动到当前正在执行的程序集。还是没什么。DLL位于K:\Installer\Bin\TestProject.DLL中。我在admin下运行此程序,因此它对Dll具有权限。

解决了这个问题。将我的代码更改为:

AppDomainSetup domainSetup = new AppDomainSetup 
                             {PrivateBinPath = binFolder+"\\TestProject.dll"};
AppDomain ad = AppDomain.CreateDomain("New domain",null, domainSetup);

TestClass remoteWorker = (TestClass)ad.CreateInstanceFromAndUnwrap(
                          binFolder+"\\TestProject.dll",
                          typeof(TestClass ).FullName);

我明白了。将我的代码更改为:

AppDomainSetup domainSetup = new AppDomainSetup 
                             {PrivateBinPath = binFolder+"\\TestProject.dll"};
AppDomain ad = AppDomain.CreateDomain("New domain",null, domainSetup);

TestClass remoteWorker = (TestClass)ad.CreateInstanceFromAndUnwrap(
                          binFolder+"\\TestProject.dll",
                          typeof(TestClass ).FullName);

您是否尝试捕获
ReflectionTypeLoadException
异常?也许“TestProject.dll”有一些运行时无法解析的依赖项。其中唯一包含的是系统dll。如何解决这些问题?是否尝试捕获
ReflectionTypeLoadException
异常?也许“TestProject.dll”有一些运行时无法解析的依赖项。其中唯一包含的是系统dll。这些问题如何解决?