1

私は次のことをしようとしています:

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 を使用して、他のアプリ ドメインからインスタンスを作成しましたが、矛盾が発生しました。

ありがとうございました。

4

1 に答える 1

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);
    }
}
于 2012-04-25T13:21:48.773 に答える