How to Implement Service Behavior in an Activity?

Adding activities to ReceiveActivity is the same as adding activities to any other workflow. Note that, when ReceiveActivity completes, execution passes to the calling method.

Activities that are added to ReceiveActivity are not limited in their functionality; there are no special rules for activities that run on a service.

For more information about the various workflow activities that you can implement, see Windows Workflow Foundation Activities

Invoking the Service

To invoke the service in a client application, you must first add a service reference to the client application and then add code to the calling class to bring the service namespace into scope.

To call a method on the service, create an instance of the service proxy, call the service, and then handle any return values that may result from the workflow call.

Remember to close the service proxy after you call the workflow and execute the required functionality. This is good coding practice and ensures that any resources that you use are disposed of in a timely fashion. This reduces the memory usage of your application and increases efficiency. Although a single service proxy may not cause a problem in most situations, it is good practice to close objects when you are no longer using them to reduce the amount of processing that is required by the garbage collector and to free up system resources more quickly.

To invoke your workflow service, you must create an instance of the service proxy and then call methods on the proxy object.

The following code examples show the full client class that creates a proxy for a workflow service and then calls a method on that service. The service is a model of an online shopping basket and exposes a method to retrieve the total price of the items in the basket. The code first creates the BasketServiceClient proxy object for the service and then calls the basketTotal method, which returns a decimal-formatted value that represents the total cost of the items in the basket. The code examples then write this value to the console by using the currency format.

 

using PublishingWorkflowDemoClient.BasketServiceContract;

 

namespace PublishingWorkflowDemoClient

{

  class Program

  {

    static void Main(string[] args)

    {

      // Create a proxy object for the service workflow.

      BasketServiceClient client = new BasketServiceClient();

 

      // Invoke the method on the service.

      // This will start a workflow instance implicitly.

      decimal basketTotal = client.ProcessBasket();

      Console.WriteLine("Basket total: {0:c}", basketTotal);

 

      // Close the client.

      client.Close();

    }

  }

}

 

Tags: