Using Reflection to dynamically expose your Business Logic through a Webservice.


Introduction:

Many people are using web services to communicate with their business logic. There are many advantages to this - Using this approach allows a wide range of flexibility in the architecture that would otherwise be very hard to come by. However, there are also a few disadvantages. One disadvantage is the amount of tedious work involved in keeping your web service methods in-sync with your business logic methods. This article will show you how you can avoid those issues, while still enjoying all the benefits of using web services.

The Reasoning:

I recently designed and built an application which used web services for business layer communication. The interface used a custom component to get data, and the custom component used the web services to communicate with the business layer. This allowed the interface to be deployed (almost) anywhere we wanted, and also gave us the ability to secure (via SSL) all communication. Our architecture was similar to this:

Interface <-> Communication Component <-> Web Service <-> Business Logic <-> Data Access Layer

Note that the Business Logic classes contained static methods to process data before being sent to the Data Access Layer, or returned to the Communication Component.

This was working great for about the first two weeks while we worked on the main system functionality. However, as time went on, we began adding more and more methods to the business logic that needed to be exposed via the web service. This was consuming a tremendous amount of time, as we had a one-to-one ratio of web services to business logic classes. Every time we added a new business logic class, we had to make a new web service, make the proxy class for the web service, keep the proxy class in-sync with the web service, and keep the web service in-sync with the business logic. It was quickly becoming more trouble than it was worth.

We had a hard deadline, and a very tight schedule. What we needed was a way to automate or simplify the maintenance associated with using web services. After tossing around some ideas (such as code generators - we already used one to generate classes from DB tables), I came up with the idea of using reflection to dynamically invoke methods in the business logic and return their results through the web service. After a 1/2 hour or so I had the first prototype, and about 2 hours later I had a component that I felt would work in a production environment.

The Setup:

Let's assume that you already have some classes developed. These classes can be thought of as "Data Transfer Objects" (DTOs). One of these classes is "CustomerData", which provides data on a particular customer. There are several ways you want to be able to access a Customer. You will either use the Customer's ID, or you will use an Order Number. You also have an "OrderData" class that you need to access. For the Order class you need to be able to either access a single order or every order for a given customer (ArrayList). The business logic classes will be called "Order" and "Customer" respectively.

Normally, for this type of situation, you would have 2 web services - One for returning CustomerData objects, and one for returning OrderData objects (you could pack them into one web service, but that gets crowded when dealing with a large number of classes). You would also have two methods in each of those web services. The web service methods would be called from your interface layer, and then they would call your business layer to get the data required. So for the normal situation, we've got two classes, two web services, and two methods in each web service.

For example:

Customer.LoadByCustomerID() <-> Customer Web Service <-> Customer Business Logic
Customer.LoadByOrderID() <-> Customer Web Service <-> Customer Business Logic
Order.LoadByOrderID() <-> Order Web Service <-> Order Business Logic
Order.LoadAllForCustomerID() <-> Order Web Service <-> Order Business Logic

Using reflection, you can have one web service, with two methods, handle each and every single call you would ever need to make to your business layer.

For Example:

Customer.LoadByCustomerID() <-> Generic Web Service <-> Customer Business Logic
Customer.LoadByOrderID() <-> Generic Web Service <-> Customer Business Logic
Order.LoadByOrderID() <-> Generic Web Service <-> Order Business Logic
Order.LoadAllForCustomerID() <-> Generic Web Service <-> Order Business Logic

The Code:

The following is the code for implementing a generic web service. I called this the "BusinessPipe" for my project.

[WebService(Namespace="http://tempuri/")]

[XmlInclude(typeof(CustomerData)),XmlInclude(typeof(OrderData))]

public class BusinessPipe : System.Web.Services.WebService

{

          private const string BUSINESS_ASSEMBLY = "My.Business.Assembly";

          #region Component Designer generated code

          //Required by the Web Services Designer

          private IContainer components = null;

          ///

/// Clean up any resources being used.

          ///

          protected override void Dispose( bool disposing )

          {

                    if(disposing && components != null)

                    {

                             components.Dispose();

                    }

                    base.Dispose(disposing); 

          }

          #endregion

 

          private Type AccessType(string typeName)

          {

                    Type type = null;

                    Assembly assembly = System.Reflection.Assembly.Load(BUSINESS_ASSEMBLY);

                   if(assembly == null)

                             throw new Exception("Could not find assembly in BusinessPipe! Assembly: " +

                                                         BUSINESS_ASSEMBLY);

                             type = assembly.GetType(BUSINESS_ASSEMBLY + "." + typeName);

                             if(type == null)

                                       throw new Exception("Could not find type!\nAssembly: " + BUSINESS_ASSEMBLY +

                                                                   "\nType: " + typeName);

                                        return type;

          }

          ///

          /// Executes a method on the Business Logic and returns whatever object that method returns.

          ///

          /// The class in the Business Logic to reference.

          /// The method that you want to execute in the class.

          /// The arguments to send to the method.

          /// The same object that the business logic method returns.

          [WebMethod]

          public object ExecuteMethod(string typeName, string method, params object[] arguments)

          {

                   object returnObject = null;

                   Type type = AccessType(typeName);

                   try

                   {

                             returnObject = type.InvokeMember(method,

                             BindingFlags.Default | BindingFlags.InvokeMethod,

                             null, null, arguments);

                   }

                   catch

                   {

                             //Do some custom exception handling here.

                             throw;

                   }

                   return returnObject;

          }

          ///

          /// Executes a method on the Business Logic and returns the same ArrayList that the method returns.

          ///

          /// The class in the Business Logic to reference.

          /// The method that you want to execute in the class.

          /// The arguments to send to the method.

          /// The same object that the business logic method returns.

          [WebMethod]

          public ArrayList ExecuteArrayMethod(string typeName, string method, params object[] arguments)

          {

                   ArrayList returnObject = null;

                   Type type = AccessType(typeName);

                   try

                   {

                             returnObject = type.InvokeMember(method,

                             BindingFlags.Default | BindingFlags.InvokeMethod,

                             null, null, arguments) as ArrayList;

                   }

                   catch

                   {

                             //Do some custom exception handling here.

                             throw;

                   }

                   return returnObject;

          }

}

Notes:

Notice how, at the top of the web service, I have included two XmlInclude statements. These two statements are required so that the framework knows how to serialize the OrderData and CustomerData objects. Also, the assembly which contains your business logic MUST be referenced from the web service. If it is not, your web service will have no idea how to get to the assembly. One last thing - notice that there are actually two public methods for this web service - ExecuteMethod() and ExecuteArrayMethod(). This is because the web service will not correctly serialize an ArrayList if the return type is not ArrayList.

Disadvantages:

There are a couple of disadvantages to this approach:

  1. You lose intellisense for the web service and it's method. This is a disadvantage if you're planning on having your web service be consumed by another party, or if you have developers who are unfamiliar with the business logic code.
  2. There is no built-in security to restrict the methods in your business logic that are accessible

While these are certainly issues, I feel that they can be addressed and corrected relatively easily:

  1. To allow intellisense, you could easily create 'proxy' classes that do nothing more than hand off requests/responses to/from the web service. However, this takes away one of the advantages of the dynamic web service, since you would then have to keep the proxy class in-sync with the business classes.
  2. To provide security, you could use custom attributes to define which business logic methods are visible, and which are not. This would be relatively easy to accomplish by using reflection to check the attributes before calling Type.Invoke().

Up Next
    Ebook Download
    View all
    Learn
    View all