fam*_*kin 5 .net reflection reflection.emit dynamic .net-assembly
我想在集成测试中动态创建程序集,以便测试一些程序集操作类.如果我使用以下代码来创建测试程序集:
var domain = AppDomain.CurrentDomain;
var builder = domain.DefineDynamicAssembly(
new AssemblyName(assemblyName),
AssemblyBuilderAccess.Save,
directory);
builder.Save(fileName);
Run Code Online (Sandbox Code Playgroud)
然后一切运行正常,程序集在所需的位置创建,但作为其中一部分,它们也加载到当前AppDomain,我不想要.
所以我想使用单独的创建程序集AppDomain:
var domain = AppDomain.CreateDomain("Test");
...
Run Code Online (Sandbox Code Playgroud)
但是运行代码会在该行引发异常var builder = domain.DefineDynamicAssembly(...);:
System.Runtime.Serialization.SerializationException:在程序集'mscorlib中键入'System.Reflection.Emit.AssemblyBuilder',Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'未标记为可序列化.
我不知道这与呼叫DefineDynamicAssembly非当前有什么关系AppDomain.我在网上找到的主要是关于在不同的域中执行程序集.也许我在这里尝试做的只是太具体,太高级甚至根本不推荐,但它可以让我测试我们所有的装配操作代码.
有人可以指点我正确的方向吗?
我通过在其他 AppDomain 中执行代码来使其工作,就像建议的那样。
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);
});
Run Code Online (Sandbox Code Playgroud)
请注意,您必须在 AppDomainSetup 上指定 ApplicationBase 才能在其他 AppDomain 中找到委托。