Dynamic code execution is a powerful feature that allows applications to be extended with code that is not compiled into the application. Users can customize applications and developers can dynamically update code easily. In this article, Rick takes a look what it takes to execute code dynamically with the .Net framework and introduces a class that simplifies the tasks by wrapping the details of the process in an easy to use interface that only requires a few lines of code.
Assemblies and Namespaces
In order for code to compile properly it needs both a physical reference to an assembly and any namespace references in the source code. Both are required for the compiler to be able to properly identify and validate your types in the compiled code. You need to provide physical assemblies via the CompilerParameters.ReferencedAssemblies propety. It points to a physical DLL or EXE that contains the types you want to include in your code. You also have to add the appropriate namespace imports to your source code which means using (CSharp) or import (VB) commands for each namespace used. Remember that you may have more than one namespace you need to include for a single physical assembly. This can become cumbersome if you want build generic code as the namespace directives tend to be placed at the top of the document. The wwScripting class handles this with an AddAssembly and AddNamespace methods that handle adding the appropriate assemblies and delays creating of the assembly source code until the final compilation.
What’s an Application Domain?
With application domains .Net provides a hosting container inside of a running process that isolates code and data into separate sub applications or domains. In simplistic terms you can think of an Application Domain as a Process within a process that provides the ability to isolate different sets of code. Code and data available in one application domain within a single process is not directly accessible from another application domain. You can however access it through special code designed to instantiate and access types in other domains.
Application domains are useful for providing specific context to an application component. They are also necessary, as described in this article, if you need to unload assemblies at any point. Since an assembly loaded into an AppDomain can never be unloaded from within the domain the only way to release them is to unload the entire domain.
Accessing Code and Data in a different domain requires the use the .Net Remoting framework which provides mechanisms using proxies and stubs that are very similar to the way DCOM operates. These mechanisms allow access to AppDomains in the same process, in a different process and across machine and network boundaries.