http://www.developer.com/

Back to article

.NET Remoting Versus Web Services


May 6, 2003

With the advent of .NET and the .NET Framework, Microsoft introduced a set of new technologies in the form of Web services and .NET remoting. .NET remoting and ASP.NET Web services are powerful technologies that provide a suitable framework for developing distributed applications. It is important to understand how both technologies work and then choose the one that is right for your application.

The Web services technology enables cross-platform integration by using HTTP, XML and SOAP for communication thereby enabling true business-to-business application integrations across firewalls. Because Web services rely on industry standards to expose application functionality on the Internet, they are independent of programming language, platform and device.

Remoting is .a technology that allows programs and software components to interact across application domains, processes, and machine boundaries. This enables your applications to take advantage of remote resources in a networked environment.

Both Web services and remoting support developing distributed applications and application integration, but you need to consider how they differ before choosing one implementation over the other. In this article, I will show the differences between these two technologies. I will present samples for each type of implementation and identify when to use which technology.

DCOM

If you are a real Microsoft platform developer then you have done some work on COM and interface based components. When it comes to distributing your program logic, you are almost tied to Distributed COM (DCOM).

DCOM is a very proprietary RPC-based communication protocol for COM-based distributed component architectures. Even though DCOM allows us to create scalable and reliable architectures in the Intranet environment, there are a lot of problems with DCOM when you try to integrate with different platforms and technologies in an Internet environment.

A Look at .NET Remoting

.NET Remoting uses a flexible and extremely extensible architecture. Remoting uses the .NET concept of an Application Domain (AppDomain) to determine its activity. An AppDomain is an abstract construct for ensuring isolation of data and code, but not having to rely on operating system specific concepts such as processes or threads. A process can contain multiple AppDomains but one AppDomain can only exist in exactly one process. If a call from program logic crosses an AppDomain boundary then .NET Remoting will come into place. An object is considered local if it resides in the same AppDomain as the caller. If the object is not in the same appdomain as the caller, then it is considered remote.

In .NET remoting, the remote object is implemented in a class that derives from System.MarshalByRefObject. The MarshalByRefObject class provides the core foundation for enabling remote access of objects across application domains. A remote object is confined to the application domain where it is created. In .NET remoting, a client doesn't call the methods directly; instead a proxy object is used to invoke methods on the remote object. Every public method that we define in the remote object class is available to be called from clients.

When a client calls the remote method, the proxy receives the call, encodes the message using an appropriate formatter, then sends the call over the channel to the server process. A listening channel on the server appdomain picks up the request and forwards it to the server remoting system, which locates and invokes the methods on the requested object. Once the execution is completed, the process is reversed and the results are returned back to the client.

Out of the box, the remoting framework comes with two formatters: the binary and SOAP formatters. The binary formatter is extremely fast, and encodes method calls in a proprietary, binary format. The SOAP formatter is slower, but it allows developers to encode the remote messages in a SOAP format. If neither formatter fits your needs, developers are free to write their own and plug it in as a replacement.

Different Types of Remote Objects

The remoting infrastructure allows you to create two distinct types of remote objects.

  1. Client-activated objects - A client-activated object is a server-side object whose creation and destruction is controlled by the client application. An instance of the remote object is created when the client calls the new operator on the server object. This instance lives as long as the client needs it, and lives across one to many method calls. The object will be subject to garbage collection once it's determined that no other clients need it.

  2. Server-activated objects - A server-activated object's lifetime is managed by the remote server, not the client that instantiates the object. This differs from the client-activated object, where the client governs when the object will be marked for finalization. It is important to understand that the server-activated objects are not created when a client calls New or Activator.GetObject. They are rather created when the client actually invokes a method on the proxy. There are two types of server activated objects. They are:
    • Single call . Single-call objects handle one, and only one, request coming from a client. When the client calls a method on a single call object, the object constructs itself, performs whatever action the method calls for, and the object is then subject to garbage collection. No state is held between calls, and each call (no matter what client it came from) is called on a new object instance.

    • Singleton - The difference in a singleton and single call lies in lifetime management. While single-call objects are stateless in nature, singletons are stateful objects, meaning that they can be used to retain state across multiple method calls. A singleton object instance serves multiple clients, allowing those clients to share data among themselves.

A Look At ASP.NET Web Services

With the arrival of .NET, creating an ASP.NET Web service is a breezy experience with the .NET framework taking away all the complexities in creating and consuming Web services. To create a Web service, all you need to do is create a Web service class that derives from the System.Web.Services.WebService class and decorate the methods (that you want to expose as Web services) with the WebMethod attribute. Once this is done, these methods can be invoked by sending HTTP requests using SOAP.

Consuming a Web service is very straightforward too. You can very easily create a proxy class for your Web service using either wsdl.exe utility or the Add Web Reference option in VS.NET. The Web service proxy hides all the network and marshaling plumbing from the application code, so using the Web service looks just like using any other local object.



Click here for larger image

As you can see from the above diagram, the client proxy receives the request from the client, serializes the request into a SOAP request which is then forwarded to the remote Web service. The remote Web service receives the SOAP request, executes the method, and sends the results in the form of a SOAP response to the client proxy, which deserializes the message and forwards the actual results to the client.

ASP.NET Web Services Vs .NET Remoting

Now that we have understood the basic concepts of .NET remoting and Web services, let us identify the differences between these two technologies. For this, I present different factors such as performance, state management, etc and then identify which technology to use in what situations.

Performance

In terms of performance, the .NET remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In the case of Web services, the primary issue is performance. The verbosity of XML can cause SOAP serialization to be many times slower than a binary formatter. Additionally, string manipulation is very slow when compared to processing the individual bits of a binary stream. All data transported across the wire is formatted into a SOAP packet. However if your Web service performs computation intensive operations, you might want to consider using caching to increase the performance of your Web service on the server side. This will increase the scalability of the Web service, which in turn can contribute to the increase in performance of the Web service consumers. A remoting component, using the TCP channel and the binary formatter, provides the greatest performance of any remoting scenario, primarily because the binary formatter is able to serialize and deserialize data much faster.

If you use .NET remoting with a SOAP formatter, you will find that the performance provided by ASP.NET Web services is better than the performance provided by NET remoting endpoints that used the SOAP formatter with either the HTTP or the TCP channel. However the .NET remoting provides clear performance advantages over ASP.NET Web services only when you use TCP channels with binary communication.

State Management

Web services are a stateless programming model, which means each incoming request is handled independently. In addition, each time a client invokes an ASP.NET Web service, a new object is created to service the request. The object is destroyed after the method call completes. To maintain state between requests, you can either use the same techniques used by ASP.NET pages, i.e., the Session and Application objects, or you can implement your own custom solution. However it is important to remember that maintaining state can be costly with Web services as they use extensive memory resources.

.NET remoting supports a range of state management options that you can choose from. As mentioned before, SingleCall objects are stateless, Singleton objects can share state for all clients, and client-activated objects maintain state on a per-client basis. Having three types of remote objects (as opposed to one with Web services) during the design phase helps us create more efficient, scalable applications. If you don't need to maintain state, use single-call objects; if you need to maintain state in a small section of code, use single call and singletons together. The ability to mix and match the various object types facilitates creation of solid architectural designs.

Security

.NET remoting plumbing does not provide out of the box support for securing cross-process invocations. However a .NET remoting object hosted in IIS, can leverage all the same security features provided by IIS. If you are using the TCP channel or the HTTP channel hosted in a container other than IIS, you have to implement authentication, authorization and privacy mechanisms yourself.

Since ASP.NET Web services are hosted, by default, in IIS, they benefit from all the security features of IIS such as support for secure communication over the wire using SSL, authentication and authorization services.

Reliability

.NET remoting gives you the flexibility to host remote objects in any type of application including a Windows Form, a managed Windows Service, a console application or the ASP.NET worker process. If you host your remote objects in a windows service, or a console application, you need to make sure that you provide features such as fault tolerance within your hosting application so that the reliability of the remote object is not compromised. However if you do host remote objects in IIS, then you can take advantage of the fact that the ASP.NET worker process is both auto-starting and thread-safe. In the case of ASP.NET Web services, reliability is not a consideration as they are always hosted in IIS, making it easy for them to take advantage of the capabilities provided by IIS.

Extensibility

Both the ASP.NET Web services and the .NET remoting infrastructures are extensible. You can filter inbound and outbound messages, control aspects of type marshaling and metadata generation. .NET remoting takes extensibility to the next level allowing you to implement your own formatters and channels.

Since ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal data to and from SOAP messages at runtime, we can very easily customize the marshaling by adding a set of custom attributes that can be used to control the serialization process. As a result, you have very fine-grained control over the shape of the XML being generated when an object is serialized.

Ease of programming and deployment

In this section, we will consider a simple remoting object and an ASP.NET Web service to understand the complexities involved in creating and consuming them. We will start off by creating a simple remote object.

Creating a remote object

Creating a remoting object is a simple process. To create a remote object, you need to inherit from MarshalByRefObject class. The following code shows a remotable class.

using System;
namespace RemoteClassLib
{
   public class MyRemoteObject : System.MarshalByRefObject
   {
      public MyRemoteObject()
      {
         Console.WriteLine("Constructor called");
      }

      public string Hello(string name)
      {
         Console.WriteLine("Hello Called");
         return "Hello " + name;
      }
   }
}

The above code is very simple and straightforward. We start off by defining a class that inherits from MarshalByRefObject. After that we add code to the constructor of the class to write out a message to the console. Then we have a method named Hello that basically takes a string argument and appends that with the string and returns the concatenated value back to the caller. Once the remote object is created, the next step is to create a host application that hosts the remote object. For the purposes of this article, we will create a console application that reads the details of the remote object from its configuration file.

using System;
using System.Runtime.Remoting;

namespace RemoteClassLibServer
{   
   class RemoteServer
   {
      [STAThread]
      static void Main(string[] args)
      {
         RemotingConfiguration.Configure(
                "RemoteClassLibServer.exe.config");
         Console.WriteLine("Press return to Exit");
         Console.ReadLine();
      }
   }
}

In the main method, we just read the configuration settings from the configuration file using the RemotingConfiguration.Configure method and wait for the client applications to connect to it.

The configuration file used by the above hosting application looks like the following. In the configuration file, we specify that we want to expose the remote object using the TCP channel by using the channel element.

<?xml version="1.0" encoding="utf-8" ?> 
<configuration>
   <system.runtime.remoting>
      <application name="RemoteClassLibServer">
      <service>
        <wellknown mode="SingleCall"  
     type="RemoteClassLib.MyRemoteObject,RemoteClassLib"
         objectUri="MyRemoteObject">
         </wellknown>
      </service>
      <channels>
         <channel ref="tcp server" port="9000"/> 
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>

Once the hosting application is started, then client applications can start creating instances of the remote object and invoke its methods. In the next section, we will understand the processes involved in creating an ASP.NET Web service.

Creating an ASP.NET Web Service

As mentioned before, creating an ASP.NET Web service is pretty easy in VS.NET. Select the ASP.NET Web Service template using Visual Studio.NET New Project dialog box. Enter the name of the project and click OK to create the project. Once the project is created, modify the default service1.asmx file to look like the following.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;

namespace XmlWebServicesExample
{

   public class Service1 : System.Web.Services.WebService
   {
      public Service1()
      {
      }      

      [WebMethod (EnableSession=true)]
      public string HelloWorld()
      {
         return "Hello World";
      }
   }
}

As you can see from the above, the Web service class named Service1 is derived from System.Web.Services.WebService. Inheriting from the WebService class is optional and it is used to gain access to common ASP.NET objects like Application, Session, User, and Context. Then we also add a method named HelloWorld that basically returns a simple string back to the callers of the Web service. In the WebMethod attribute of the HelloWorld method, we also specify that we want to enable session state for our ASP.NET Web service by setting the EnableSession attribute to true.

Creating the consumer for the ASP.NET Web Service

You can consume the Web service by using the Add Web Reference option in VS.NET to create a proxy for the Web service. When you create a Web reference, the VS.NET IDE creates a proxy for you based on the WSDL file published by the Web service. Once the proxy is generated, you can treat the proxy class methods as if they are the actual Web service methods. At runtime, when the proxy class methods are invoked, they will connect to the actual Web service, invoke the Web service method, retrieve the results returned by the Web service and hand it back to the consumers. The following screenshot shows how to use the Add Web Reference option to create a proxy for the Web service.



Click here for larger image

So far, we have seen the steps involved in creating a .NET remoting object and an ASP.NET Web service. As can be seen from the above code, ASP.NET Web services are very easy-to-create. Consuming ASP.NET Web service is also a very simple process due to the excellent Web service support provided by Visual Studio.NET. With .NET remoting, you need to create the remote object first and then write a hosting application (assuming that you are not using IIS) to expose that remote object. You also need to make sure that the information about the remote object is retrieved from the configuration file to allow for extensibility in the future. If you all these factors into consideration, you will agree that .NET remoting objects are complex to develop and deploy.

Type Fidelity

ASP.NET Web services favor the XML schema type system, and provide a simple programming model with broad cross-platform reach. .NET remoting favors the runtime type system, and provides a more complex programming model with much more limited reach. This essential difference is the primary factor in determining which technology to use.

Putting it all together

So far, we have looked at the differences between these two technologies. Let us summarize the difference in a table.

  ASP.NET Web Services .NET Remoting
Protocol Can be accessed only over HTTP Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)
State Management Web services work in a stateless environment Provide support for both stateful and stateless environments through Singleton and SingleCall objects
Type System Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized. Using binary communication, .NET Remoting can provide support for rich type system
Interoperability Web services support interoperability across platforms, and are ideal for heterogeneous environments. .NET remoting requires the client be built using .NET, enforcing homogenous environment.
Reliability Highly reliable due to the fact that Web services are always hosted in IIS Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application.
Extensibility Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages. Very extensible by allowing us to customize the different components of the .NET remoting framework.
Ease-of-Programming Easy-to-create and deploy. Complex to program.

Though both the .NET Remoting infrastructure and ASP.NET Web services can enable cross-process communication, each is designed to benefit a different target audience. ASP.NET Web services provide a simple programming model and a wide reach. .NET Remoting provides a more complex programming model and has a much narrower reach.

As explained before, the clear performance advantage provided by TCPChannel-remoting should make you think about using this channel whenever you can afford to do so. If you can create direct TCP connections from your clients to your server and if you need to support only the .NET platform, you should go for this channel. If you are going to go cross-platform or you have the requirement of supporting SOAP via HTTP, you should definitely go for ASP.NET Web services.

Combination of .NET Remoting and ASP.NET Web Services in Action



Click here for larger image

So far, we have understood how the .NET remoting and ASP.NET Web services technologies differ in implementation. We have also had a detailed look at different factors to understand what technology to choose in what situation. Even though these two technologies are meant for different purposes, there are times where you will be able to use the combination of these technologies in your application. For example, in an application scenario where you are trying to address the needs of both internet and intranet clients, you might consider using both .NET remoting and Web services as shown in the above diagram. For the intranet .NET clients, you can use .NET remoting to enable cross appdomain communication. For the internet clients, you can expose the same functionality as Web services, allowing client applications running in different platforms to take advantage of the Web service.

Conclusion

Both the .NET remoting and ASP.NET Web services are powerful technologies that provide a suitable framework for developing distributed applications. It is important to understand how both technologies work and then choose the one that is right for your application. For applications that require interoperability and must function over public networks, Web services are probably the best bet. For those that require communications with other .NET components and where performance is a key priority, .NET Remoting is the best choice. In short, use Web services when you need to send and receive data from different computing platforms, use .NET Remoting when sending and receiving data between .NET applications. In some architectural scenarios, you might also be able to use.NET Remoting in conjunction with ASP.NET Web services and take advantage of the best of both worlds.

Source Code

Download Source Code: RemoteWeb.zip - 78 kb

About the Author

Thiru Thangarathinam has six years of experience in architecting, designing, developing and implementing applications using Object Oriented Application development methodologies. He also possesses a thorough understanding of software life cycle (design, development and testing). He holds several certifications including MCAD for .NET, MCSD and MCP. Thiru is an expert with ASP.NET, .NET Framework, Visual C# .NET, Visual Basic .NET, ADO.NET, XML Web Services, and .NET Remoting and holds. Thiru has authored numerous books and articles. He can be reached at thiruthangarathinam@yahoo.com.

# # #

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date