开发者

Trying to create class that can be passed between app domains as parameter c#

开发者 https://www.devze.com 2023-03-13 10:16 出处:网络
That is what i am trying to do: I created the class that i want to be the parameter that will be passed between two app domains. In the file ClassLibrary1.dll:

That is what i am trying to do:

I created the class that i want to be the parameter that will be passed between two app domains. In the file ClassLibrary1.dll:

    [Serializable]
    public class MyClass
    {          
        public string mystr = "NotWorking!";

         public MyClass(string _mystr)
         {
            mystr = _mystr;
         }            
         public override string ToString()
         {
             return mystr;
         }
}

Then i created another class that will be the class that will recive MyClass as parameter in otherdomainclass.dll:

public class OtherDomainClass : MarshalByRefObject, IOtherDomainClass
{
    #region Implementation of IOtherDomainClass

    private MyClass my;
    public MyClass getParam()
    {
        return my;
    }

    public void setParam(MyClass _param)
    {
        my = _param;
    }

    #endregion
}

and defined interface for that class in in iotherdomainclass.dll:

public interface IOtherDomainClass
{
    MyClass getParam();
    void setParam(MyClass _param);
}

and now I am tryi开发者_高级运维ng to run the following test :

[TestMethod()]
    public void PassMyclassBetweenDomains()
    {
        domain = AppDomain.CreateDomain(appDomainName);
        otherClass = domain.CreateInstanceFromAndUnwrap(location, "OtherDomain.OtherDomainClass") as IOtherDomainClass;
        Assert.IsNotNull(otherClass);
        otherClass.setParam(new MyClass("Working!"));
        string sparam = otherClass.getParam().ToString();
        Assert.AreEqual(sparam, "Working!");
        AppDomain.Unload(domain); 
    }

the test fails with following error:

Test method SerizalizableDataTypesTest.ParamCollectionTest.PassMyclassBetweenDomains threw exception 
    System.Runtime.Serialization.SerializationException: Unable to find assembly        'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Sorry about the long story I am not sure what part I am doing wrong. Or if all the code is wrong from the beginning could you please help me to recreate it.

Thank you very much!!!


Since the MyClass type you created is in a assembly that has not yet been loaded in the second AppDomain, consider loading that assembly directly in the 2nd AppDomain.

Your example class is more complicated than it needs to be because you are not doing anything that requires custom serialization/deserialization code. This will be easier to maintain:

[Serializable]
public class MyClass
{
   public string mystr = "NotWorking!";
   public MyClass(string _mystr)
   {
      mystr = _mystr;
   }
   public override string ToString()
   {
      return mystr;
   }
}
0

精彩评论

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