Tuesday, August 11, 2009

Create objects in remote/other AppDomains + unload assemblie(2)

Hi there...

In my previous post I showed how can you unload a assembly within an AppDomain and rebuild the assembly project without stoping the process that loaded the assembly.

In this post I'll show you how can you pass parameters to the newly created AppDomain. For this, you have to create a class that is decorated with Serializable attribute and create some properties that are the actual parameters (it is passed by value. If you want to pass by refrence, you must inherit from MarshalRefByObject - but you will stay in the main AppDomain).
[Serializable]
internal class CrossDomainObject
{
internal string Path { get; set; }
internal string Type { get ; set; }
internal object ObjectSent { get; set; }

internal void DomainCallBack()
{
//load assembly
Assembly assembly = Assembly.LoadFrom(Path);
AppDomain.CurrentDomain.Load(assembly.FullName);

//get type
Type type = assembly.GetType(Type);
if (type == null)
throw new NullReferenceException(
string.Format("Unable to get type: {0}", Type));

//create instance in remote domain
object instance= Activator.CreateInstance(type);

if (instance == null)
throw new NullReferenceException("Unable to create object in remote domain");

//get Controller property
PropertyInfo p = commandType.GetProperty("MyProperty");

if (p == null)
throw new NullReferenceException("Unable to get MyProperty property");

if (ObjectSent == null)
throw new NullReferenceException("Convert to ObjectSent failed!");

//Set value to the remote controller
p.SetValue(instance, ObjectSent , null);
}
}

The CrossAppDomainDelegate will invoke the DomainCallBack.

CrossDomainObject obj = new CrossDomainObject { ObjectSent = new List<object>(), Path = pathToAssembly, Type = typeOfInstance };
domain.DoCallBack(new CrossAppDomainDelegate(obj.DomainCallBack));

That's about it...

No comments: