I was asked to evaluate a framework recently and came across code similar to this
(I changed the class name and method name to protected the identity of the source):
AppDomain
domain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
SomeClass
theObject = (SomeClass)domain.CreateInstanceFromAndUnwrap(
System.Reflection.Assembly.GetExecutingAssembly().Location,
typeof(SomeClass).FullName);
ArrayList
array = theObject.MyMethod();
AppDomain.Unload(domain);
return array;
Let's call the code above CodeA. The code for SomeClass is something like this:
[Serializable()]
public class SomeClass
{
private ArrayList
_array;
private Type
_type;
private FileInfo
_file;
public SomeClass()
{
}
public ArrayList
MyMethod()
{
//...
}
Given the class above, what do you think was the intent of CodeA and what did it end up doing?
It appears that the author wanted to create the object in a separate AppDomain and
execute the method
MyMethod in that AppDomain.
At least that is what I assumed at the first glance. However, when I took
a closer look at the code for SomeClass, I realized
that it is marked Serializable and it doesn't derive
from
MarshalByRefObject. So, an object is created in a
new AppDomain, the constructor which does almost nothing
is executed on it, a copy of the object is then made (as it is Serializable and
not MarshalByRefObject)
and the method MyMethod is executed in the main AppDomain.
In a document, the author had explained the use of AppDomain and
how using it, the assemblies loaded by
MyMethod are unloaded right after use, and the assemblies
are not held by the application that is running.
I think that is a great idea. However, the code above doesn't do that. I ran some
tests to validate my suspicion.
AppDomain is a pretty cool concept in .NET. However,
like anything else, we need to take the time to learn it.
I encourage you to learn about AppDomains if you are
not familar with it already. It comes in handy to do some
nifty stuff. I will post an example about it if you are interested in learning about
it further.