简体   繁体   中英

Trying to create instance Application domain

I am trying to do the following:

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

Is there anything I do wrong? I the creation succeed but after when I try to use the instance of MyClass in some cases i have unexpected exception.

Edited: Found the source of the problem, I have been using dll that I loaded in current app domain to create instance from in other app domain and it caused inconsistency

Thank you.

Check the sample code to load an object in a different domain and execute the work.

You can only load the object in different object if that component dll is referenced in application.

If it's not referenced then go for 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM