Shhh... Don't Tell Anyone but I am using .NET Remoting: Part 2 - Consider making your implementation internal
In Part 1 it was suggested to use only interfaces to program against your remoted object. Another consideration for enforcing the correct usage of your remote object is to limit access to the implementation except through the interface that you defined for it.
You can do this by marking the implementation internal so that it is cannot be constructed directly except within the same assembly.
Consider the following changed code from Part 1:
Server code:
internal class HelloObject : MarshalByRefObject, IHello
{
string IHello.HelloWorld(string name)
{
return "Hello, " + name;
}
}
Shared code:
public interface IHello
{
string HelloWorld(string name);
}
The same code on the client will allow for activation of an instance of the HelloObject class:
IHello proxy = (IHello)Activator.GetObject(typeof(IHello), "tcp://localhost/Hello.rem");
But this will prevent someone from using the type outside the implementation assembly by constructing the class directly:
// this will now fail outside the implementation assembly
HelloObject localObject = new HelloObject();
This may seem a bit draconian and unnecessary but it can enforce two good early development practices:
1. If you plan on "remoting" an object in the future don't treat it as "local" during development. This can lead to performance and scalability issues that start with "But it work fine running locally on my dev box...".
2. Enforce your contract (i.e., the IHello interface) as the only way to program against your remote object. If you are planning on "remoting" an object then enforcing a common programming model, whether local or remote, can help ensure consistency and avoid issues when deploying your remote object later.
Even after following this advice you can access the implementation class locally without remoting it by using the Activator class:
IHello localObject = (IHello)Activator.CreateInstance(Type.GetType("HelloObject"));
This allows local developers to use the implementation class but keeps the programming interface common whether local or remote.
Comments
- Anonymous
November 27, 2007
PingBack from http://feeds.maxblog.eu/item_157352.html