For performance optimization, I dynamically create new types per user request using the following code:
var dynamicAssemblyName = new AssemblyName(assemblyName);
AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder moduleBuilder = dynamicAssembly.DefineDynamicModule(assemblyName);
Then I use that moduleBuilder
to emit the type.
This creates a new dynamic assembly per request. So I could end up with many of those during the lifetime of the app. So, I'm worried that the resources will be freed. Therefore, I'm using AssemblyBuilderAccess.RunAndCollect to make this possible. The msdn says:
The dynamic assembly can be unloaded and its memory reclaimed, subject to the restrictions described in Collectible Assemblies for Dynamic Type Generation.
I just didn't find how to unload the dynamic assembly and unfortunately the link to the Collectible Assemblies for Dynamic Type Generation topic is broken.
A no-longer-maintained version of that page seems to indicated that the unloading happens automatically once the emitted type gets out of scope. Can I trust this?