我正在尝试执行以下操作:
private static MyClass CreateMyClassInDomain(ApplicationDomain domain, string componentName, params object[] parmeters)
{
var componentPath = Assembly.GetAssembly(typeof(MyClass)).CodeBase.Substring(8).Replace("/", @"\");
ObjectHandle inst = Activator.CreateInstanceFrom(domain, componentPath, "MyNsp." + componentName, true, BindingFlags.Default, null,
parmeters, null, null);
return (MyClass)inst.Unwrap();
}
我做错了什么吗?我创建成功,但在某些情况下尝试使用 MyClass 的实例后出现意外异常。
编辑: 找到了问题的根源,我一直在使用我在当前应用程序域中加载的dll 从其他应用程序域中创建实例并导致不一致
谢谢。
最佳答案
检查示例代码以加载不同域中的对象并执行工作。
如果在应用程序中引用了该组件 dll,则只能在不同的对象中加载该对象。
如果没有被引用,那就去反射(reflection)吧。
namespace MyAppDomain
{
class Program
{
static void Main(string[] args)
{
// Create an ordinary instance in the current AppDomain
Worker localWorker = new Worker();
localWorker.PrintDomain();
// Create a new application domain, create an instance
// of Worker in the application domain, and execute code
// there.
AppDomain ad = AppDomain.CreateDomain("New domain");
ad.DomainUnload += ad_DomainUnload;
//ad.ExecuteAssembly("CustomSerialization.exe");
Worker remoteWorker = (Worker)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "MyAppDomain.Worker");
remoteWorker.PrintDomain();
AppDomain.Unload(ad);
}
static void ad_DomainUnload(object sender, EventArgs e)
{
Console.WriteLine("unloaded, press Enter");
}
}
}
public class Worker : MarshalByRefObject
{
public void PrintDomain()
{
Console.WriteLine("Object is executing in AppDomain \"{0}\"", AppDomain.CurrentDomain.FriendlyName);
}
}
关于c# - 尝试创建实例应用程序域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6291650/