Can an assembly generated using CodeDomProvider be deallocated?

381 views Asked by At

I want to code an app that allows the user to define GUI driven code snippets.

In this context, I aim to send these snippet definitions to a service which will be able to compile and run it (code dom, code dom provider, ...) for several purposes.

As these compiled assemblies will be generated many times, my question is about how to deallocate them when needed.

I know that assemblies loaded from a file cannot be deallocated from memory except if loaded in a separated app domain (and we need to deallocate the whole app domain).

But is it the case for assemblies compiled on the fly? And, if needed, how to generate these assemblies in a separated app domain?

For instance, is the approach indicated in this question needed in my case (here I guess the whole compilation process and runtime usage should be done in a separated app domain)?

1

There are 1 answers

2
Venson On BEST ANSWER

From my pow you are mixing up two thing here:

  1. Compiliation and
  2. Execution

You can compile as much code as you like to with the CodeDom Provider and write the resulting cs code anywhere, then you dispose the CodeDom writer (CSharpCodeProvider) and the used memory is gone.

When executing code its something complete different. There are several libs that provide you with a way of executing Cs code but they (mostly) all share a same problem by default. Code will be executed within the executing application. This requires an AppDomain because executing anything in a .net Environment is assigned to one. If you want to separate the "untrusted" code execution from your host code, another AppDomain is required.

Scripting(c#) Libs in C#:

Note: CS script execution is a hell of Security concerning. There are unlimited ways of breaking out of an AppDomain and without a lot of effort in making your appdomain save against those attacks you will have a huge whole in your application security concept. I have made an Evaluation just recently and decided to use javascript as scripting language instead (With the Chakara.Core engine).