【问题标题】:Trying to create instance Application domain尝试创建实例应用程序域
【发布时间】:2011-09-11 14:37:03
【问题描述】:

我正在尝试执行以下操作:

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 从其他应用程序域中创建实例并导致不一致

谢谢。

【问题讨论】:

  • 有什么异常?你期望什么例外? :)
  • 意外的异常是什么?

标签: c# applicationdomain


【解决方案1】:

检查示例代码以加载不同域中的对象并执行工作。

如果在应用程序中引用了该组件 dll,您只能将对象加载到不同的对象中。

如果没有被引用,那就去反思。

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多