gpt4 book ai didi

.net - 在非当前 AppDomain 上使用 DefineDynamicAssembly 动态创建程序集时出现异常

转载 作者:行者123 更新时间:2023-12-04 10:05:55 24 4
gpt4 key购买 nike

我想在集成测试中动态创建程序集,以测试某些程序集操作类。如果我使用以下代码创建测试程序集:

var domain = AppDomain.CurrentDomain;

var builder = domain.DefineDynamicAssembly(
new AssemblyName(assemblyName),
AssemblyBuilderAccess.Save,
directory);

builder.Save(fileName);

然后一切运行正常,程序集在所需位置创建,但作为其中的一部分,它们也被加载到当前 AppDomain ,这是我不想要的。

所以我想使用单独的 AppDomain 创建程序集:
var domain = AppDomain.CreateDomain("Test");

...

但是运行代码会在 var builder = domain.DefineDynamicAssembly(...); 行抛出异常。 :

System.Runtime.Serialization.SerializationException: Type 'System.Reflection.Emit.AssemblyBuilder' in assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.



我不知道这与调用 DefineDynamicAssembly 有何关系在非当前 AppDomain .我在网上找到的主要是关于在不同的域中执行程序集。也许我在这里尝试做的事情太具体、太高级甚至根本不推荐,但它可以让我测试我们所有的汇编操作代码。

有人可以指出我正确的方向吗?

最佳答案

我通过执行另一个 AppDomain 中的代码来让它工作,比如 suggested .

var appdomain = AppDomain.CreateDomain("CreatingAssembliesAndExecutingTests", null,
new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase });

appdomain.DoCallBack(() =>
{
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("temp"), AssemblyBuilderAccess.Run);
var module = assembly.DefineDynamicModule("DynModule");
var typeBuilder = module.DefineType("MyTempClass", TypeAttributes.Public | TypeAttributes.Serializable);
});

备注您必须在 AppDomainSetup 上指定 ApplicationBase 才能在另一个 AppDomain 中找到委托(delegate)。

关于.net - 在非当前 AppDomain 上使用 DefineDynamicAssembly 动态创建程序集时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13468157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com