vrijdag 10 december 2010

C# - remoting and serialization

The following I copied from an old blog somewhere else.

Ever thought of using remoting to distribute your objects?
Ever thought of using serialization to persist your objects?
Ever thought of combining the two?

You might want to read this first.

To use your objects for remoting you need to make them inherit from MarshalByRefObject.
That's perfectly serializable as long as your objects are not used accross application domain boundaries.
In other words, that's perfectly serializable as long as you don't use them for remoting (how convenient!).

Because if you ever do, the private MarshalByRefObject.ServerIdentity gets set. And it isn't serializable.

There are articles on this issue all over the internet. In fact, Microsoft acknowledges the issue but refuses to fix it. If you want to read more try reading the article titled "Serialization of MarshalByRefObject fails after a remoting identity has been set" here: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97623
A lot of articles on this issue focus on bringing a fix for the issue. I feel they might be missing the obvious. Persistence is about preserving an object's state at a certain moment in time. But does it have to be instantaneous?
So persisting an object used for remoting fails. But persisting an object not used for remoting succeeds. That may sound pretty useless, but remember, your object initially hasn't been used for remoting yet. So if you only ever had to persist objects not used for remoting yet you'd be fine.
Let's do that. Add a copy constructor to your class that inherits from MarshalByRefObject and needs persistence. If you need to persist such an object call the copy constructor to create a new one and use that object for serialization. MarshalByRefObject.ServerIdentity hasn't been set on the new object yet because it hasn't been used for remoting yet.
Fixed.

Geen opmerkingen:

Een reactie posten