开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜