2011年8月16日 星期二

[C#] Load/Unload Assembly & Create Instance

Implementation:

LocalAssembly.cs:
using System;
using System.IO;
using System.Reflection;

namespace AssemblyLoader
{
public class LocalAssembly
{
public LocalAssembly(string name)
{
this.name = name;
}

public void Load(string assemblyLocation)
{
localAssemblyDomain = AppDomain.CreateDomain(name);

localAssembly = localAssemblyDomain.Load(
new AssemblyName() {
Name = Path.GetFileNameWithoutExtension(assemblyLocation),
CodeBase = assemblyLocation
}
);
}

public void Unload()
{
AppDomain.Unload(localAssemblyDomain);
}

public object CreateInstance(string typeName)
{
return localAssembly.CreateInstance(typeName);
}

private string name;
private AppDomain localAssemblyDomain;
private Assembly localAssembly;
}
}
  • Call Load() method to load an assembly in a separated domain.
  • Call Unload() method to unload it.
  • Call CreateInstance() method to create an instance in the current domain. Please cast its return value to the proper type.

沒有留言:

張貼留言