Unchained Service Factory


Intent

Provide a single Web service method to allow the Web service provider the flexibility of easily interchanging the services without directly affecting bound Web service clients . Unlike the Chained Service Factory, however, this pattern uses .NET Reflection to implement late binding. Late binding allows the Web service the ability to instantiate any back-end business object without requiring code changes at the Service Factory level. Combining a factory object with the services of Reflection provides the design with a truly loosely coupled architecture on which to build.

Problem

This pattern solves the same problems as does the Chained Service Factory. The difference lies in the problem of forcing the developer to make changes to the switch/case code in the Service Factory class if any new business objects were to be added to the framework. Using Figure 4.3, if additional FinancialProduct derived objects were to be added to the system, the switch/case statement code in FinancialServiceFactory would have to change. The change would reflect the instantiation of the new class, based on that new service being requested by a complying Web client. As mentioned in the Chained Service Factory, business objects instantiated by the "factory" in this manner are early bound to the service (thus the word chained in the pattern name ).

Figure 4.3. Unchained Service Factory implementation class diagram.

graphics/04fig03.gif

Early binding means naming a type at compile time or design time (e.g., using the new keyword against a class) ”in essence, building the vtable before execution. Late binding, on the other hand, refers to the technique of resolving a given type at runtime, as opposed to compile time. Late binding eliminates the need to know or name a type during design. It allows you to resolve and later reference a type and its members at runtime. This solution is then implemented in a much more dynamic and loosely coupled fashion. Although early binding will perform slightly faster in most respects, it does require recompilation of the code if any new features were to be added. Late binding protects the code from future deliberate recompilations. However, it does so at the penalty of slightly slower code performance. This is due to the fact that runtime type resolution generally will take longer than a vtable lookup. The tradeoff between slightly slower performing code versus increased flexibility must be weighed by you.

In the case of the Chained Service Factory, the added flexibility that is received by implementing late binding outweighs the slight decrease in performance. Using this pattern, however, only the initial instantiation and execution of the factory method is actually late bound. From the point of instantiation and initial execution onward, the remaining business object will be known and, thus, early bound. Also, the fact that there are only a few types needing to be resolved increases the benefit received from using late binding.

The Unchained Service Factory shows how using Reflection can aid you in eliminating code changes to the Service Factory. No longer does there need to be a fixed switch/case statement where each class must be predetermined and instantiated with the new keyword. The Web client requests the service as before by bundling the service request in some generic type, such as our DataSet. Instead of building of a switch/case statement, the developer can now extract the service name from the metadata and using that string, dynamically instantiate the target business object by name. Besides using .NET's Reflection classes (explained below), the designer also must name the targeted business objects using, at least in part, the same string that is requested by the Web client. Naming data types (classes, in our case) allows the developer to use text strings passed into the Web service method as our identifier of the class. This identifier is then used by the Reflection libraries to perform the runtime lookup and creation.

Anyone who has developed in Visual Basic, especially those who have built a similar factory using programmatic identifiers for this very purpose, should be already familiar with this technique. Using Visual Basic, a client could pass in a string of the programmatic identifier of the COM component they wished to create, and the receiving factory could then create that component on that value. Now that .NET no longer requires the use of programmatic identifiers (everything is based on name types), the type name itself must be used to provide this same feature. The difference here is that .NET is inherently early bound, and the developer must use Reflection to implement late binding.

Forces

Use the Unchained Service Factory pattern when:

  • Business function interfaces may change in the future.

  • Multiple Web service methods are provided on the server.

  • Web service clients cannot be controlled.

  • Changing client code would be difficult.

  • Changes to a "chained" or early bound implementation of a factory would be inconvenient (to avoid having to edit code on a regular basis for all directly callable business functions).

  • Late binding a publicly executable business function will not significantly impede performance.

Structure

Figure 4.4. Unchained Service Factory generic class diagram.

graphics/04fig04.gif

Consequences

  1. Provides a true late-bound loosely coupled Web service . Unlike the Chained Service Factory, the developer no longer must edit any code when business objects are added to the system. Using .NET Reflection services to invoke all initial business objects, you can now easily add business objects into the system without forcing code compilations due to the factory having to early bind to any of the new business objects. This also isolates the Web clients from having to make any code changes on the client, even when calling significantly enhanced areas of the system, as long as the business objects added on the server conform to a standard contract and can be instantiated from the factory.

  2. Adds a small performance hit to the factory interface . Using .NET Reflection services to instantiate the business object at that factory interface will slightly decrease performance. This is due to the fact that a business service must be " discovered " at runtime and, therefore, cannot be early bound. The impact should be minimal because all business services from the initially instantiated business object inward should be early bound. Only the initially instantiated business objects (FinancialProduct) or fa §ades require reflection.

  3. Provides a single entry point into the system . As stated in the above pattern, only one method acts as the entrance into the framework. This allows greater control over who is calling into the system and more control over interface standards. It also provides a simple way of announcing services to the provider. Frameworks and services (especially within a large organization) are constructed all of the time, but the key to selling them is providing a simple yet generic approach to calling them. With Reflection, any business function can be represented.

  4. Eases system monitoring . As stated in the above pattern, because all traffic is routed through this single point of contact, monitoring the system becomes simpler. Using HTTP monitoring applications (such as IIS Loader) simplifies the developer's profiling efforts because system load can primarily be determined through this one entry point.

  5. It isolates any Web client from Web method signature changes . As stated in the above section, it provides a single entry point into the system and a generic signature that allows future services to be added without affecting the external interface.

  6. It provides the ability to add future framework objects into the system . Related to item 3, this also allows future subframeworks to be added easily into the system. See the Chained Service Factory section for details.

  7. Calling simple Web service-based business functions requires more setup. See the Chained Service Factory section for details.

Participants

  • ServiceClient (CreditCard Customer) ” A Web service client for the credit card customer. This becomes the Web service proxy.

  • Service (Financial Service Factory) ” Contains a Web method that acts as a single point of entry into the system. This entry point unpackages the service request, instantiates the correct service (e.g., Service Fa §ade), and calls a standard method on that service.

  • Fa §ade (Financial Product) ” Defines a standard method to route the business request to the appropriate product. See the Chained Service Factory section for details.

  • ConcreteFa §ade (Credit Card) ” Implements the standard method for the business request optionally acting as a "controller" or fa §ade to other subordinate downstream business objects.

  • Assembly ” .NET framework class. This represents the currently running assembly from which to load the requested objects.

  • Type ” .NET framework class. This represents the type of the requested object.

  • MethodInfo ” .NET framework class. This represents the method of the requested service.

  • Activator ” .NET framework class. The object that creates the requested object once all reflection types are identified and created.

Implementation

Implementing this pattern is identical to that of the Chained Service Factory with one exception. Instead of building of what could eventually become a large switch/case statement (depending on how many business object types will be created), the developer must now use Reflection. Using the data types from the System.Reflection namespace, we now dynamically instantiate our FinancialProduct object or any other requested object by name. In the first step of the Execute() method, the service string is extracted as before in the Chained Service Factory. A reference to the current running assembly is then retrieved (explained below), and the business object type we are looking to create is returned. Retrieving this type requires the string we packaged in the DataSet (returned in the PacketTranslator.GetService()). Once retrieved from the helper method, the string is concatenated to a fully qualified path that tells the reflection method GetType() which object we are looking for. Once the type is returned, we can create the object in memory by calling CreateInstance() using a Reflection "Activator." Don't worry, all of the Reflection material will be explained shortly. From that point on, we retrieve a method to call, bind our parameters, and invoke the method. The trick to calling any method in our newly created business object is guaranteeing that the method signature of that business object will always be consistent. Not providing a standard method signature on a creatable and callable business object in this design would significantly complicate the code. In fact, all business objects in this example implement a factory method themselves , which is called, you guessed it, Execute() . This is not a hard requirement, but it will make plugging in future business objects (that will be "launchable" from this Service Factory) much simpler and much cleaner.

Listing 4.3 shows this in action.

Listing 4.3 Unchained Service Factory implementation using Reflection.
 [WebMethod] public DataSet ExecuteLateBound(DataSet dsPacket) {     DataSet ds = new DataSet();     Assembly oPMAssembly = null; Type oFacadeType = null;     object oFacade = null;     MethodInfo oFactoryMethod = null;     object[] oaParams = null;     string sService;     // GetService code listed in ChainedServiceFactory section sService = PacketTranslator.GetService(dsPacket); // load the assembly containing the facades     oPMAssembly = Assembly.GetExecutingAssembly(); // return the type and instantiate the facade class based // on the service name passed oFacadeType = oPMAssembly.GetType("CompanyA.Server" + "." + sService + "Facade"); oServiceFacade = Activator.CreateInstance(oFacadeType); // Return the factory method for the chosen facade // class/type     oFactoryMethod = oFacadeType.GetMethod("Execute"); // bind the parameters for the factory method - single param // in this case - dsPacket (DataSet)     oaParams = new object[1];     oaParams[0] = dsPacket;     // invoke the Execute factory method of the chosen facade     ds = (DataSet) oFactoryMethod.Invoke(oFacade, oaParams);     return ds; } 

To understand the code completely, however, we need to dive a little into the .NET Reflection services.

Technology Backgrounder ”.NET Reflection Services

For those who've been developing Java applications for some time, Reflection should be very familiar. In fact, .NET's implementation of its Reflection services matches that of Java's, almost feature for feature. For the rest of the folks who have not worked with any form of Reflection services before, this may seem a bit new. For COM developers, introspecting services through a set of standard interfaces is nothing new. Utilizing the basics of COM development and the QueryInterface() method, a developer can dynamically inspect the interface makeup of most COM components . Along those lines, using facilities such as type library information also provides a means for introspecting the types and services of binary entities. Reflection services provide exactly what the Java runtime intended ”to provide a runtime programmatic facility to introspect and manipulate objects without knowing their exact type makeups at compile time.

Using types defined in the System.Reflection namespace in .NET, the developer can programmatically obtain metadata information about all data types within .NET. This can be used for building tools along the line of ILDasm.exe, where assemblies can be examined for their underlying makeup. Also, Reflection provides the ability to utilize late binding in an application that requires it (e.g., implementing our pattern). For those developing .NET/COM interoperability applications that implement late binding through IDispatch, this can also come in very handy. Using data types in the reflection namespace, one is able dynamically to load an assembly at runtime; instantiate any type; and call its methods, passing any of the required parameters. Instead of declaring those types at design time, the developer uses the abstracted data types included in Reflection. There are data types that represent objects, methods, interfaces, events, parameters, and so forth. To bind the generic types of Reflection with those that the developer actually wants to work with, normal strings are used to name them at runtime. This may seem a little strange until you begin working with Reflection types, so the best suggestion is just to start writing a few examples. Some of the more useful members of the System.Reflection namespace are included in Table 4.1.

The first data type in the reflection namespace you need to familiarize yourself with is the Type data type. This isn't a misprint; the actual name of the data type is Type . Type is a class that provides methods that can be used to discover the details behind other data types. However you cannot directly call "new" on the Type class. It must be obtained through another "type-strong" data type, such as our Product object below:

Table 4.1. Some Members of the System.Reflection Namespace

Assembly

Define and load assemblies, load modules that are listed in the assembly manifest, and locate a type from this assembly and create an instance of it at runtime.

Module

Discover information such as the assembly that contains the module and the classes in the module. You can also get all global methods or other specific, nonglobal methods defined on the module.

ParameterInfo

Information discovery of things such as a parameter's name, data types, whether a parameter is an input or output parameter, and the position of the parameter in a method signature.

PropertyInfo

Discover information such as the name, data type, declaring type, reflected type, and read-only or writeable status of a property, as well as getting/setting property values.

EventInfo

Discover information such as the name, custom attributes, data type, and reflected type of an event. Also allows you to add/remove event handlers.

FieldInfo

Discover information such as the name, access modifiers (e.g., public), and the implementation details of a field, as well as getting/setting field values.

MethodInfo

Discover information such as the name, return type, parameters, access modifiers, and implementation details (e.g., abstract) of a method. Use the GetMethods or GetMethod method of a Type object to invoke a specific method, as we do in this example.

 Product oProduct = new Product(); Type t = oProduct.GetType(); 

Another technique is to do something like this:

 Type t = null; t = Type.GetType("Product"); 

Something you will see quite often when using attributes or any other method that requires a System.Type data type ”getting a Type object using the typeof() keyword:

 Type t = typeof(Product); 

Once we have a Type object, we can get to the objects methods, fields, events, etc. For example, to get the methods (once we have the Type object), we call t.GetMethods() or t.GetFields(). The return values of these calls return other data types from the Reflection namespace, such as MethodInfo and FieldInfo, respectively. Hopefully, you're starting to get the picture.

Finally, to get our pattern working, we first retrieve the current assembly by calling GetExecutingAssembly(). This retrieves an Assembly object so that we can later return a Type object representing a data type requested by the Service Factory:

 Assembly oPMAssembly = null; / load the assembly containing the facades oPMAssembly = Assembly.GetExecutingAssembly(); oFacadeType = oPMAssembly.GetType("NamespaceA.ProductFacade"); 

Once we have the assembly, we can retrieve the business object using a normal string, such as the one passed to us in the Service Factory method Execute(). Once we have a returned Type object, we can now actually instantiate the object. This requires using what is called the Activator class in Reflection. The Activator is the key to implementing late binding in .NET. This class contains only a few methods, one of which is called CreateInstance(). Here we pass our newly returned Type object, which results in the runtime creation of our desired business object. Once our object is created, the next step is to bind parameters and retrieve a MethodInfo object to call. This is accomplished by first binding the method parameters as an object array, retrieving a MethodInfo type by calling GetMethod("<method to call>"), and finally calling Invoke on that newly returned MethodInfo type, as shown:

 oFactoryMethod = oFacadeType.GetMethod("Execute"); oaParams = new object[1]; oaParams[0] = dsPacket; // invoke the Execute factory method of the chosen facade ds = (DataSet) oFactoryMethod.Invoke(oFacade, oaParams); 

That's it. Now the developer can pass any data type string into the Service Factory, and as long the requested business object implements a standard interface, any object can be created. This is just the tip of the iceberg for the Reflection services, and I strongly urge you to explore other features of this powerful namespace for yourself. Be forewarned, however, that because there will be some performance penalty when using Reflection, it should be used sparingly.

Related Patterns

  • Factory Method (GoF)

  • Chained Service Factory (Thilmany)

  • Proxy (GoF)

  • Abstract Factory (GoF)

  • Strategy (GoF)

Challenge 4.1

When would you implement both Chained and Unchained Service Factory patterns as part of the same architecture?

See Chapter 6 on Product X to see why they did it (pages 303- “309).



.NET Patterns. Architecture, Design, and Process
.NET Patterns: Architecture, Design, and Process
ISBN: 0321130022
EAN: 2147483647
Year: 2003
Pages: 70

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net