ARTICLE

Using Reflection to dynamically expose your Business Logic through a Webservice

Posted by Zach Smith Articles | Web Service in VB.NET December 04, 2006
Many people are using web services to communicate with their business logic. There are many advantages of this approach with some issues. This article will show you how you can avoid those issues, while still enjoying all the benefits of using web services.
 
Reader Level:

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

    Inherits System.Web.Services.WebService

    Private BUSINESS_ASSEMBLY As String = "My.Business.Assembly"

    'Required by the Web Services Designer

    Private components As IContainer = Nothing

    '/

    '/ Clean up any resources being used.

    '/

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)

        If disposing And Not (components Is Nothing) Then

            components.Dispose()

        End If

        MyBase.Dispose(disposing)

    End Sub 'Dispose

   

    Private Function AccessType(ByVal typeName As String) As Type

        Dim type As Type = Nothing

        Dim [assembly] As [Assembly] = System.Reflection.Assembly.Load(BUSINESS_ASSEMBLY)

        If [assembly] Is Nothing Then

            Throw New Exception("Could not find assembly in BusinessPipe! Assembly: " + BUSINESS_ASSEMBLY)

        End If

        type = [assembly].GetType((BUSINESS_ASSEMBLY + "." + typeName))

        If type Is Nothing Then

            Throw New Exception("Could not find type!" + ControlChars.Lf + "Assembly: " + BUSINESS_ASSEMBLY + ControlChars.Lf + "Type: " + typeName)

        End If

        Return type

    End Function 'AccessType

 

    '/

    '/ 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.

   Public<WebMethod()>  _

   Function ExecuteMethod(typeName As String, method As String, ParamArray arguments() As Object) As Object

    Dim returnObject As Object = Nothing

    Dim type As Type = AccessType(TypeName)

      Try

         returnObject = type.InvokeMember(method, BindingFlags.Default Or BindingFlags.InvokeMethod, Nothing, Nothing, arguments)

      Catch Else

    'Do some custom exception handling here.

         Throw

      End Try

      Return returnObject

   End Function 'ExecuteMethod

 

    '/

    '/ 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.

   Public<WebMethod()>  _

   Function ExecuteArrayMethod(typeName As String, method As String, ParamArray arguments() As Object) As ArrayList

    Dim returnObject As ArrayList = Nothing

    Dim type As Type = AccessType(TypeName)

      Try

         returnObject = type.InvokeMember(method, BindingFlags.Default Or BindingFlags.InvokeMethod, Nothing, Nothing, arguments)

      Catch Else

    'Do some custom exception handling here.

         Throw

      End Try

      Return returnObject

   End Function 'ExecuteArrayMethod

 

End Class 'BusinessPipe

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().

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (http://www.c-sharpcorner.com/).

share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Diagram
Become a Sponsor