Exception when dynamically creating assemblies using DefineDynamicAssembly on a non-current version of AppDomain

I want to dynamically create assemblies in integration tests to test some assembly manipulation classes. If I use the following code to create test builds:

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

then everything works fine, assemblies are created in the required place, but as part of this, they are also loaded into the current AppDomain , which I do not want.

So, I would like to create assemblies using a separate AppDomain :

 var domain = AppDomain.CreateDomain("Test"); ... 

But running the code throws an exception in the line var builder = domain.DefineDynamicAssembly(...); :

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

I do not know how this relates to calling DefineDynamicAssembly on a non-current AppDomain . All that I find on the Internet is mainly about building assemblies in separate domains. Perhaps what I'm trying to do here is too specific, too advanced, or even not recommended at all, but that would allow me to check out all of our assembly manipulation code.

Can anyone point me in the right direction?

+4
source share
1 answer

I got it by running the code in another AppDomain, for example.

 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); }); 

Note that you need to point the ApplicationBase to the AppDomainSetup in order to find the delegate in another AppDomain.

+1
source

Source: https://habr.com/ru/post/1447150/


All Articles