Sunday, January 6, 2008

Hiện thực hóa kiến trúc SOA với .NET

(Realizing a Service-Oriented Architecture with .NET)
Web Services have emerged as a key strategic capability for integrating business processes, data, and organizational knowledge.

This article is meant to be a practical discussion guide to building a .NET application in a service-oriented architecture. We will consider real-world goals, real-world obstacles, and experience-based solutions. I quickly concede the approaches discussed here are not exhaustive or infallible. This paper is focused on application development, not application integration. We will specifically consider architectural issues and component design issues.

The Potential of Web Services

So why all the hype? Web Services obviously have great potential. It's a way to integrate at many different levels. Consider this example. A single consumer application (perhaps interacting with your company over the Internet) wants to engage the company in some business process. To facilitate that business process, the company internally invokes processing that spans two discreet systems (A and B). However, through a service-oriented architecture, the entire end-to-end business process is exposed to the consumer application as a single service.

Hình ảnh
Figure 1. Exposing separate LOB applications as a single service.

Architectural Considerations

A good architecture emphasizes a separation of responsibilities. For example, the presentation tier manages presentation components; the business logic tier manages business logic components; and the data access tier manages data access components.

This separation provides for fault tolerance, easier maintenance, and future-proofing. A good service-oriented architecture is nothing new, just a smart way of separating (and exposing) a component's responsibilities. It builds on classic object-oriented (OO) ideas.

In a service-oriented architecture, clients consume services, rather than invoking discreet method calls directly. In a 3-tier model (Figure 2), objects are marshaled across process boundaries through the proxy/stub techniques we know from COM. This provides benefits such as location transparency. The same techniques are used in .NET Remoting via channels and sinks. The basic philosophy is that one tier should only communicate with the tier contiguous to it.

One disadvantage to object-orientation at an architectural level is the number of communication links. Client code is responsible for traversing complex object models and understanding details about domain-specific logic. In a service-oriented model, we introduce a further "layer of indirection". This alleviates some of the pain associated with traversing complex object models. The services layer, denoted below in Figure 3 by the cloud, provides black-box functionality.

Hình ảnh
Figure 2. A typical 3-tier application architecture

Hình ảnh
Figure 3. A service-oriented application architecture

Designing Services and Objects

In a service-oriented design, services should be course-grained. Course-grained services are modeled after and align to business processes.

Objects should be fine-grained and align to real business entities. These discreet objects provide the detailed business logic. Specificity is good when building discreet business objects. This is also a very successful way to codify organizational knowledge. Each business object is responsible for its own behavior and business rule implementation, such as updating a database table, sending an email, or placing a message on a queue.

Services provide the orchestration of the detailed business objects to expose a full service to the consumer. Services are responsible for orchestrating calls to discreet business objects, managing the responses, and acting accordingly. Service methods may invoke and manage several business objects.

Service methods align to business processes by design. Class methods align to detailed object-level operations by design.

Consider the following example in Figure 4. Notice we have a Web service called BookStoreService and a Web method called orderBook(). This single Web method instantiates and manages 3 separate objects, Book, Order, and OrderDetail.

Hình ảnh
Figure 4. Designing services and objects.

Design Considerations

Minimize Roundtrips

A design goal should be to design services to minimize round-trips. This was true with COM and it continues to be true with .NET and Web Services.

Recall in classic n-tiered distributed architectures that conventional wisdom said it was better to move 1000 bytes across process boundaries 1 time, rather than moving 1 byte across 1000 times. We would optimize method signatures and design stateless components, and we would use database helper routines to convert ADO recordsets to XML to provide a lightweight payload for distributed applications.

With SOAP and Web Services, we generally see the same approach. However, we need to take it one step further. We should now consider using the Web Service as a service, not just a data pump, and XML as a self-describing package, not just a payload.

Align Web Methods to Forms

Web methods should be designed to perform an entire service for an entire form. In short, our design goals are:

Provide a course-grained Web method at the form level
Have the Web method invoke whatever business objects it needs
Return to the consumer the whole service result, like a DataSet with numerous tables within it

Consider the following example. We may be designing a search form to search a bookstore for certain titles. To support this search screen in this figure, we would design a Web method called GetSearchScreenInfo which returns a DataSet that has a number of tables within it. This Web Method is designed to provide all the information the form needs to draw itself on the load event.

Hình ảnh
Figure 5. Align service methods to forms

On this particular form, we need two lists just to populate the screen: a list of valid publishers, and a list of valid categories. Rather than making two calls to the Web Service (one for each dropdown), we design our Web method to provide everything we need in a single call. We service the loading of the search form in a single interaction. Later work, such as performing the search or drilling into details, is handled by separate Web methods.

Behind the scenes, our web method is invoking and managing all the business objects it needs to satisfy the request.

Moving Data Between Tiers

Data can be moved between architectural tiers as DataSets, serialized objects, raw XML, etc. -- but design your solution to be consumed. DataSets are .NET specific objects that serialize nicely but are intended for other .NET applications. If your application needs to interoperate with, for example, a J2EE solution, DataSets may be too troublesome to employ because the J2EE side would not readily understand a DataSet.

Serializing business objects is also an option. But remember that the full object is not marshaled. The object's public properties and data members are serialized and shipped, but the calling client cannot re-inflate the object and access its private data members or methods.

XML is, of course, an obvious choice also. XML formatted exchanges are a solid and proven technique for moving data around any distributed architecture.

Distributed Transactions

Web methods can act as the root of a distributed transaction. These transactions are managed by the Distributed Transaction Coordinator (DTC). Our Web Service classes must reference the System.EnterpriseServices namespace, and can then use the ContextUtil class to use the SetAbort() and SetComplete() methods. This provides for declarative transaction control.

Each object enlisted by the Web method is a child object and will participate in the transaction and "vote" on the outcome. This provides the best fit for keeping objects granular enough to manage their own data from a persistent store, while still allowing them to be orchestrated by a transaction-root controller.

Transactional context is managed by the root. Web Methods must be adorned with the TransactionOption attribute, something like this:

Mã:
[WebMethod(TransactionOption=TransactionOption.RequiresNew)]


Child objects need nothing special. They do NOT need to derive from the ServicedComponent base class. The same child object can be enlisted in a transaction for one Web method, but not enlisted in a transaction for another Web method.

Exception Handling

Exceptions should be considered a rarity. They should be thrown only in exceptional situations, not in normal branching. Each caller should catch exceptions and deal with them appropriately. In its simplest form, an exception could be bubbled up the call stack from the backend to the UI and presented to the end-user. However, each step up the stack should have processing done at that layer. All exceptions thrown over SOAP get shipped as SOAP exceptions. For example, we might throw an exception if someone tried to log on inappropriately using this simplified code:

Mã:
Throw New BadPasswordException()

The caller would need to catch that exception, like this:

Mã:
Catch x1 As BadPasswordException // do something

In this example, the caller catches the particular exception and reacts to it. However, if the Web Service threw an application exception to the end-user client, the exception is transformed into a SOAP exception. In fact, the client program must specifically catch that SOAP exception, as in Figure 6.

Mã:
catch e as System.Web.Services.Protocols.SoapException


Hình ảnh
Figure 6. Throwing exceptions over a SOAP connection.

The client program must catch at least 3 different types of exceptions. The first is SoapException.

On the client, SoapExceptions should be caught for any middle-tier exceptions. This is useful for throwing exceptions from the middle tier application logic. However, ANY middle tier exceptions will be thrown as a SoapException.

We can encode the inner exception to be business-problem specific information we need. As an example, we can pass a SoapException with a meaningful message, such as "Database access error", so that the client can deal with it.

Next the client should catch WebExceptions. This is useful when the network goes down in the middle of an end-user's session.

Finally, the client must catch client-side exceptions. These are thrown by client-side processing, and are something local to client, like FileNotFound.

Conculsion

The key messages to take away from this discussion about constructing .NET applications in a service-oriented architecture are as follows:

Service-oriented architecture is rooted in object-orientation but adds a layer of abstraction. I like to think that service-orientation is not a departure from object-orientation, but rather an evolution. Services orchestrate calls to discreet business objects to satisfy requests. Objects are enlisted, behind the scenes, to formulate a response.

The openness of the technologies is exciting and easy to use. The current industry work on standards around UDDI, WSDL, Web Services, etc. promises that more and more applications can be constructed from constituent services rather than re-invented domain-specific code.

The statelessness of the technologies can be a challenge for performance heavy applications. Be aware of the non-functional requirements of the solution you want to build. Sometime line-of-business applications desire long-running transactions that are better suited to other distributed application technologies.

Design your solution for Web Services - you will have different approaches than you would for Remoting or DCOM. Again, remember that service-orientation is appropriate for some business applications, but not all. A service-oriented architecture is one possible architecture pattern to consider when designing solutions.
(Chip Irek)

No comments:

Post a Comment