Friday, January 2, 2009

Remoting objects (yes I know it's not 2001) without using the MSDN Way

Ok very few people use Remoting Services any more but it's good in a pinch for quick and dirty way of doing distributed applications.

Now when I went to first use Remoting I struggled to make it fully usable as the books I was using (as well as a quick Google and MSDN lookup) had me all using code like so:


// Create an instance of a channel
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel);

// Register as an available service with the name HelloWorld
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(SampleObject),
"HelloWorld",
WellKnownObjectMode.SingleCall );


The above code instantiates (calls: new SampleObject() ) an object to be able to accessed remotely..but it cannot take any arguments in the ctor !!

This ended up causing me no end of grief, because if I wanted to write a remoting test, I was pretty much stuck with whatever "new SampleObject()" initialized. Now I was forced to open up configuration changes via setters!

Eventually I scratched the whole thing when I found out Castle Windsor had a remoting facility and just used that to handle my remoting needs and it works quite well.

Looking through Castle Trunk they use RemotingServices like so:


internal static void Marshal(object instance, ComponentModel model)
{
MarshalByRefObject mbr = (MarshalByRefObject) instance;

if (!Convert.ToBoolean(model.ExtendedProperties["remoting.published"]))
{
string uri = (string) model.ExtendedProperties["remoting.uri"];

// key logic is here
RemotingServices.Marshal(mbr, uri, model.Service);

model.ExtendedProperties["remoting.published"] = true;
}
}




So with RemotingService.Marshal(object, uri ) is the key here it takes an already intialized class and makes it "remote" and available as a service to another client somewhere else. So much more flexible!

No comments: