Share via


Shhh... Don't Tell Anyone but I am using .NET Remoting: Part 3 - Use interfaces and serializable types in your contract

Now that you expose the your remote object through a CLR interface, that interface should limit itself to interfaces and serializable types as parameters and return values.  This guideline is really just an additional follow-on to rule one about using only CLR interfaces.

Let's expand on the original example from part 1.  The original interface from part 1 is below:

public interface IHello
{
   string HelloWorld(string name);
}

This works fine since the the HelloWorld accepts and returns only strings which are serializable. What if we want to add a factory pattern that returns newly created remote objects or make the HelloWorld method take a custom type.  For these scenarios we should continue to use interfaces and define serializable data types for passing of information.

First let's add the factory pattern:

public interface IHelloFactory
{
   IHello CreateHelloService();
}

This factory pattern is also an interface and simply returns the original IHello interface.  The implementation of this interface would inherit from MBRO and new up a HelloObject but all the clients of this service would continue to use the shared interfaces for programming rather than the implementation classes.

Now we expand HelloWorld to take the new HelloMessage custom data types that is serializable.

public interface IHello
{
   HelloMessage HelloWorld(HelloMessage message);
}

[Serializable]
public class HelloMessage
{
   private string SenderName;
   private string Text;
   // property accessors omitted for brevity
   ...

   public HelloMessage(string sender, string text)
   { ... }
}

By sticking to this guidance we continue to deploy only the types necessary to share the contract.  Shared interfaces (IHello and IHelloFactory) and serializable data types (HelloMessage) are the only pieces of the contract that consumer of our remote service need ever program against.  Even if you move to a different activation, hosting or communications technology these same contract types will be reusable and are not .NET Remoting specific.  Upgrading from this model to a future technology will be simple and mechanical since the programming interface will remain constant once an instance of the service is activated and accessible.

The new client code will allow for activation of the factory and then creation and consumption of the IHello service:

IHelloFactory factoryProxy = (IHelloFactory)Activator.GetObject(typeof(IHelloFactory), "tcp://localhost/HelloFactory.rem");
IHello helloProxy = factoryProxy.CreateHelloService();
HelloMessage returnMessage = helloProxy.HelloWord(new HelloMessage("Me", "Hello"));