dimanche 4 décembre 2016

Deserialize method of BinaryFormatter class doesn't work if it calls through Invoke method of MethodInfo class

I have a custom AppDomain which is named "servicedomain". ServiceLibrary.dll was loaded into this domain by using:

serviceAssembly = Assembly.LoadFrom(path);

Into my ServiceLibrary.dll I have two methods which convert my custom class to array of bytes and vice versa.

public static byte[] TransformMessageToBytes(NotificationMessage msg)
        {
            if (msg == null)
                throw new ArgumentNullException(nameof(msg));

            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                binFormatter.Serialize(stream, msg);
                return stream.ToArray();
            }
        }

public static NotificationMessage TransfromBytesToNotificationMessage(byte[] array, int offset, int count)
        {
            if(array == null)
                throw new ArgumentNullException(nameof(array));

            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                stream.Write(array, offset, count);
                stream.Seek(0, SeekOrigin.Begin);
                return binFormatter.Deserialize(stream) as NotificationMessage;
            }
        }

I uses DoCallBack which takes lambda to execute my code.

serviceDomain.DoCallBack(() =>
{ 
    // for example
    // create instance of NotificationMessage by using reflection
    // Invoke convertation methods
});

I have a problem from this moment. TransformMessageToBytes method works pretty good, but I gets an error when I tries to invoke TransfromBytesToNotificationMessage. Deserialize method of BinaryFormatter doesn't work. The error is:

Could not find assembly "ServiceLibrary".

I don't understand why Serialize method is works? Have you any ideas how to solve a problem with Deserialize method? Thanks!





Aucun commentaire:

Enregistrer un commentaire