Home > Articles > Programming > Windows Programming

This chapter is from the book

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

04fig03.gifFigure 4.3. Unchained Service Factory implementation class diagram.

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

04fig04.gifFigure 4.4. Unchained Service Factory generic class diagram.

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020