Service tiers in a tiered architecture

Source: Internet
Author: User
Tags net xml

Http://www.uml.org.cn/zjjs/201009141.asp

Introduction

Introduction

The service layer does not perform any tasks directly. What it does is make a reasonable arrangement for some of the business objects you provide. The service layer is well aware of the business logic layer and is well aware of the domain model. For example: You use the business logic layer of the database table model schema, and the service layer interacts with the dataset.

It is clear that the service layer reasonably arranges the business components, while also reasonably arranging the application of services, workflows, and other components of the business logic.

Responsibilities of the service layer

The service layer is an extra layer that sets a boundary between two layers.

What is the purpose of the service layer?

There are many application principles in the industry are very important, in the design of the software should pay attention to: separation of attention, low coupling, high cohesion. When we talk about modifying an existing object, how to make it expose low coupling, the first thing to think about is to add more abstractions. In the We see that the class action relies on the concrete class strategy, because the strategy class is referenced in one of the action's methods.

  

How to reduce dependence? And there is a principle: programming for the interface, do not program for implementation. When designing, you should hide the strategy class in the action class. Define an interface for the strategy class, and then define a factory class to create a specific strategy instance so that strategy modifications no longer affect the action class and reduce the action class's dependency on the Strategy class.

In addition to the high-level abstraction of the factory model, there are many patterns in the service layer. The service layer is located between a pair of interface layers, maintaining their low coupling and relative independence, but can communicate well with them. Most of the time, the service layer we see is defining a boundary between the presentation layer and the business logic layer. This is a common solution.

  

Reasonable arrangement of system behavior

As you can see in, the service layer wants the presentation layer to mask the implementation details of the business logic layer. But, not only did he do the work. is correct, but not all.

In his core, every user-driven interaction has two participants: a user interface implemented by the presentation layer, and a module that the service layer implements to respond to user behavior. This also proves that the service layer is not just a reasonable arrangement of business logic, but it also deals with the presentation layer.

Any interaction that originates from the presentation layer will find a response at the service level. Based on the input data received, the service layer controls the business components, including services, workflows, and domain models, and of course access to the database access layer is required.

Is the service layer just doing database operations directly? is not very accurate, business logic will include workflows and business services. The business logic should be independent of any database details.

The service layer is the boundary between the presentation layer and the other layers, which gets and returns the data transfer object, and then transforms the data transfer object into an instance of the appropriate domain model class. Each method exposed through the service layer integrates other services, workflows, and database operations through ORM.

What is a service?

Aside from the relevant technology, the Word service simply represents a layer of software requests sent to another layer. The service layer, a collection of services, is a layer in the middle of two layers of communication.

What is service orientation?

Service orientation is a design approach that considers business processes as a series of interconnected services. Service orientation is not the technology itself, but a different way of doing things that describe how the business operates.

Services vs. classes

In the design of the application, the service orientation allows you to use the stand-alone components of the fixed interface. These components can be replaced at any time and will not affect the system as long as the protocol of the interface is not changed.

Benefits of using the service tier

The service layer provides a unique protocol between the user interface and the other tiers, allowing you to focus on application logic. Application logic is part of the business logic that arises directly from the use case.

On the server side, the service layer method that is executed, reasonably arranges the required logic, through the coordination domain model, the Special Application service, the workflow.

Without a service layer, the presentation layer invokes the business logic layer directly. When you complete a task, you may need to make multiple remote calls. For performance, this is not a good thing.

Service level Combat

Introduction

The service layer defines another layer in the middle of the two layers of the interaction, typically between the presentation layer and the business logic layer. This middle tier is just a collection of classes that implement the application's use cases.

Services and service-oriented presence make the solution more valuable and successful. Compared to the presentation layer, the service layer provides a loosely coupled, service layer that provides agreed protocols, reusability, and cross-platform deployment. The service, like other classes, allows you to adjust the total number of abstractions you need.

The real-world presentation layer is primarily the user's front end. Everything the user does is through the presentation layer and the user interface.

Enterprise-class applications, there may be multiple data representation interfaces. An interface can be either a user interface or every supported platform, such as mobile apps, Web, WPF, Windows, Silverlight, or other software platforms. Another interface might be a back-end application, pass in data or fetch data, and transform him. There may also be an interface that is an internal processing logic in a system consolidation scenario using the application's connector agent.

The service layer responds to input from the presentation layer. Accordingly, the presentation layer does not care about the operation and the module at the other end. The important thing is that the module declares what it can do.

Both the presentation layer and the service layer do not contain business logic. The presentation layer only knows the coarse-grained interfaces provided by the service layer, and the service layer knows only a series of workable protocols that deal with the essence of the details: transaction, resource management, coordination, and data messaging.

Service layer in real life examples

The emergence of SOA, consistent with the advent of the service layer, strengthens the concept of the service layer and makes him more attractive. Some argue that using SOA in a multi-tiered architecture is creative. It's pointless to argue about this, as if there were chickens or eggs first.

Many programmers and architects have failed to understand the rationale behind the use of the service layer in actual use. Below, let's analyze a real-life example.

Many of us have experience as junior programmers. At some point, we will meet a defiant boss. The boss may say, "Hi, we need to customize a system for our customers right away."

Did you hear that? The boss is the presentation layer. The boss is concerned with sending a simple command to the manager. In his eyes, the manager exposes a list of tasks and responsibilities. The boss doesn't care how the manager actually accomplishes the task, but he knows what the manager in the agreement between the company and the manager should do (the agreement also mentions that if the manager does not meet the requirements, it will be replaced). The manager is the service layer. Eventually, the manager coordinates other resources to accomplish this task.

If you look around, in real life you will find many examples of service layer patterns. For example, a child needs pocket money from his parents, an editor asks to change a document, you take cash from an ATM, and so on.

When to use the service tier

The service layer should be used in any somewhat complex application. If you are in a simple document management system, or are a quick-build site, it is likely that there will be no payoff in establishing a service layer in a site that is only available for several weeks.

In a tiered system, there is no reason not to use the service tier. One possible exception is the simple front end and a range of application services that simply satisfy the use case. In this case, the service layer is probably just a transmitter, with no task combination to work. A simple service layer is not as good as calling the business logic layer directly.

Conversely, when you have multiple front ends and a lot of application logic, it's better to keep the application logic in one place rather than keeping the copy in every application interface.

Benefits of the service layer

The service layer adds abstraction, decoupling two layers of interaction. When you want to get a better system, you should build a service layer. The service layer uses coarse-grained, remote interfaces to minimize the number of communication between the presentation layer and the business layer.

When you implement a service layer through a service (for example, WCF), you can feel other benefits, such as changing the binding information by configuration.

Disadvantages of the service layer

Because abstraction is a major advantage of the service layer, it can be a bit overdone for a simple system.

Service tiers are not required to use service technologies such as WCF. In the performance layer of ASP, you can call the Code-behind class the service layer. Using WCF instead of a normal class can be a bit overdone and likely to degrade performance. Considering the use of WCF in your system, you need to consider performance and if performance degradation is intolerable, choose other service tier technologies.

What scenarios the service layer applies To

The presentation layer invokes the service layer. Is it a remote call, or is it a local call?

Flower's recommendation for distributed object Design is: Don't scatter your objects. We can understand it as: "Unless it is necessary, or is good." As you know, the necessities and benefits are actually easily variable and difficult to quantify, but in some special scenarios they are easy to identify.

So, what scenario is appropriate for the service layer? Generally speaking, if you have a service layer that can easily move across tiers, that's a good thing. At this point, a service technology such as WCF is the right tool.

If the client is a Web page, the service tier is best located on a local Web server. If the site succeeds, you can detach the service tier to a standalone application server to increase scalability.

If the client is a desktop app, the service layer is deployed to a separate physical layer and accessed remotely. This approach is similar to the software+services architecture, where the client has nothing but the GUI and all the application logic is at the far end. If the client uses Silverlight and the service layer is published on the Internet, you can build a perfect Ria (Rich Internet application) app.

Combat Service Layer Mode

Implementing a service layer relies on two technology choices. The first choice is what the method or invocation serves as the basis for the service layer. Use a normal class or service? If you choose a service, which service is the implementation technology to choose? In Windows or Yes. NET platform, your choice is relatively small. You can choose a WCF service, an ASP. NET XML Web service, or a service like rest.

If you have a. NET Framework has some understanding, you should know that creating a WCF service or a Web service is like creating a normal class, and then adding some attribute. Of course, there are many details to consider, such as the WSDL Web Service Description Language Web Services Description language, WCF configuration, and data protocol. The service is ultimately a class that contains additional content.

Design the class of the service layer

The classes used by the service layer should expose a protocol, whether it is a WCF protocol or an implementation interface. Implementing an interface is a good practice because it clearly describes what a class can do and what it will do. The interface uses DTOs to receive and return data, recommending coarse-grained methods so that it can minimize network traffic and maximize network throughput.

How do you map the required methods to interfaces and classes? On the basis of the use case, list the required methods, and then divide them into logical groups. Each group establishes its own service or is a class.

In most cases, your result is to create a service class, Orderservice,customerservcie, and so on for each entity in the problem domain. These are all needed by the application. However, if the user behaves relatively small and behaves similarly, then a service class may be sufficient. Otherwise, a single service class will quickly become larger and will be difficult to maintain and change.

In general, we think there are no strictly defined guidelines, such as: each entity has its own service, or a service needs to satisfy all of the user's entities. The service layer adjusts between the presentation layer and other parts of the system. The service layer includes coarse-grained services (also use case-driven) that implement use cases in their programming interfaces.

The service layer is independent of the rest of the system and is only an interface that invokes the internal processing flow for the presentation layer. If the use case changes, you will most likely just modify the service layer without modifying the business logic. In a relatively large application, for the programming interface of the service layer, you should first look at your use case and then use a common method to organize the methods in the class.

Classes that implement a service layer

We recommend that each class implement an interface. If you choose WCF, this is a strict requirement and is a good way to do it overall.

Code

[ServiceContract (namespace= "HTTP://WWW.DSN.COM/WCF")]
public interface IOrderService
{
[OperationContract]
BOOL Submit (BeautyCode.Entity.Order order,beautycode.entity.communuser user,out BeautyCode.Entity.CException Exception);

[OperationContract]
List<beautycode.entity.order> Findorders (BeautyCode.Entity.OrderFind find, BeautyCode.Entity.CommunUser user ,
Out BeautyCode.Entity.CException exception);

[OperationContract]
BeautyCode.Entity.Order getbyorderseqno (String orderseqno, BeautyCode.Entity.CommunUser user,
Out BeautyCode.Entity.CException exception);
}
Code

[ServiceBehavior (instancecontextmode= Instancecontextmode.percall)]
[Aspnetcompatibilityrequirements (Requirementsmode=aspnetcompatibilityrequirementsmode. Allowed)]
public class Orderservice:servicebaseimpl, IOrderService
{

private void ThrowException (BeautyCode.Entity.CommunUser user)
{

}


public bool Submit (BeautyCode.Entity.Order Order, BeautyCode.Entity.CommunUser user, out BeautyCode.Entity.CException exception
{
throw new NotImplementedException ();
}

Public list<beautycode.entity.order> findorders (BeautyCode.Entity.OrderFind Find, BeautyCode.Entity.CommunUser User,
Out BeautyCode.Entity.CException exception)
{
throw new NotImplementedException ();
}

Public BeautyCode.Entity.Order getbyorderseqno (string orderseqno, BeautyCode.Entity.CommunUser user,
Out BeautyCode.Entity.CException exception)
{
throw new NotImplementedException ();
}
}

First, assume that the interface uses domain model objects directly. In the example above, the Order class represents the order entity we established in the domain model. If we use the actual domain model object, we assume that the pattern of the domain model is used in the business logic. If you use the schema of the data table model, the order class in the above code should be replaced with a DataTable. We'll come back to the discussion on the DTO.

The Submit method needs to integrate the service within the application, check the user's account status, check the validity of the goods in the order, and synchronize the manufacturer's product information. The Submit method is a typical service-layer approach that provides a single protocol for the presentation layer, with multiple steps to operate with different domain models and business logic.

The Findorders method returns an order collection, GETBYORDERSEQNO returns a specific order. Also, suppose that we use the domain model's pattern in the business logic layer, there is no dedicated data transfer object. Many architects recommend that the Create, Read, Update, Delete (CRUD) methods do not appear at the service layer. The Findorders and Getbyorderseqno methods are essentially the read methods in crud.

Moreover, the method relies on your use case. These methods must be available if a user clicks a place in a use case to display the list of orders or the details of a single order.

Handling Roles and security

The Findorders method should only return orders that the current user can see.

If you consider security as a matter of fact, you should check the identity of the caller in each of the service layer's methods, and deny the invocation of the method to the unauthorized user.

If you do not want to re-authenticate the user in each method, you need to add attribute to the service layer's methods to implement authentication.

The service layer acts as a gatekeeper, usually without the need to transfer role information to the business logic layer to verify, unless there are good reasons. However, if there is such a good reason, it is also good that you have to pass the role information to the business logic layer.

The relevant model of the service layer

1 Introduction

We view the service layer as a collection of services exposed to the user interface. Most of the time, we'll find that the service layer approach is easy to meet the user's behavior. In most enterprise applications, CRUD is a common operation. There are times when multiple entities are processed in a single operation.

The service layer includes role management, data validation, notification, tuning of data returned to the user interface, or the possible need to integrate the system.

Some design patterns may help when it comes to these. Here are some patterns that are helpful in implementing the service layer.

2 remote Appearance mode remotes facade pattern

The remote appearance mode is used to modify the granularity of the methods that have been implemented, and the appearance mode does not implement any new functionality. It just wraps a layer of different skins on top of the original API. Why do you need an appearance pattern?

2.1 Motives for using the appearance mode

The appearance mode changes the way an existing object is accessed. Cite an example of a freight forwarder's online service. Every freight forwarder has its own API for registering shipments, tracking goods and other services, and their details may not be available in your application. By creating a unified API, you can hide the details of the forwarder API and make your application have a clear interface.

In other words, if you want your interface to handle a simple interface, these imperatives force you to create another look. In fact, this is the precise definition of the classic remote appearance pattern.

The benefit of the appearance pattern is that you are allowed to define a coarse-grained interface on top of a series of well-defined fine-grained objects.

Object-oriented allows you to create a lot of small objects, separation of duties, fine-grained objects. However, these objects are not suitable for distribution. In order for these objects to be valid, you need to make some adjustments. You don't want to change any implementations of fine-grained objects, but you need them to perform a batch of operations. In this case, you need to create a new method to move the larger data. When you do this, you are actually modifying the existing interface granularity, which is to create the appearance pattern. Let's go back to the example of a freight order. With your own API you can send multiple orders without using the Forwarder's API to send a single order, here we assume that the forwarder does not support multiple orders for the API.

2.2 Remote appearance mode and service layer

By design, the service layer essentially has a coarse-grained interface, because it tends to abstract a certain number of small operations to use for the client. At this point, the service layer is already a façade pattern on top of the business logic layer and the domain layer object.

public interface IOrderService
{
void Create (Order o);
List<order> FindAll ();
Order FindByID (int orderID);

}

If you use WCF, you need to add Protocol attribute on the service layer interface.

Code

[ServiceContract]
public interface IOrderService
{
[OperationContract]
void Create (Order o);

[OperationContract]
List<order> FindAll ();

[OperationContract]
Order FindByID (int orderID);

}

All non-basic types of data require the addition of datacontract tags. When WCF runs, these tokens automatically create a data transfer object DTO for the specified type.

[DataContract]
public class Order
{
[DataMember]
int OrderID {get; set;};

[DataMember]
DateTime OrderDate {get; set;};

}

If you are using ASP. XML Web service. Do not add any markup to the class above, just add the WebMethod tag on the method of the service layer class.

You may need a more coarse-grained interface when using the appearance mode, or you might use a dto, or you'll use it. The following interface is decoupled from the domain object, focusing more on interaction with the presentation layer.

public interface IOrderService
{
void Create (Orderdto o);

List<orderdto> FindAll ();

Orderdto FindByID (int orderID);

List<orderdto> searchorder (querybyexample query);
}

Orderdto may be a subset of the domain class order or an order (which may be consolidated depending on the object OrderDetail), Querybyexample is a specialized class that transmits some conditions of the user interface to the service layer, and I prefer to define the write find class, such as Orderfind. There are some query conditions, such as: time, number, amount, and so on.

In fact, if the user interface changes relatively large, you need to modify the service layer. You may need to refactor the service layer, or use the appearance mode to wrap it out again.

3 Data Transfer Object mode

DTOs (Data Transfer Object data transfer objects) are just an object that transmits data across the application boundary, primarily to minimize the round-trip of the network.

3.1 Motives for using DTO mode

There are two main motives. One is to minimize the round-trip of the network when you invoke the remote object, and the other is to maintain a loose coupling between the front-end display and the domain model of the backend.

In most cases, DTOs have only attributes and no operations. DTOs play an important role in the domain model scenario. Not in all cases, the presentation layer can use the local domain object directly. If the service layer and the presentation layer in the same physical layer, such as the presentation layer is the form of Web pages, can be used directly. If the service layer and the presentation layer are not on the same physical layer, it is best not to exchange data through domain objects. The main reason is that your domain objects may be dependent on one another, or even a circular reference, which can seriously affect their serialization capabilities or even the problem of serialization failure.

Personal understanding of why a DTO is needed and when it is needed is for informational purposes only:

On the same level, there is no problem with the transmission of the object over the network, so the domain model can be used directly, and the efficiency is high, there is no network transmission and delay.

In the same layer, there is the problem of network transmission, the domain model contains both data and operations, the data can be transferred between the layers, but the operation can not be transmitted. Moreover, in order to understand the objects in the domain model and the objects transferred, and the granularity of the domain model, the transmission domain model may need to be called multiple times to meet the interface display, which will increase the number of round trips of the network.

At the same time, the interface may display content from several domain model objects, or several properties in a domain model object. This is why a DTO is created separately to transfer data between tiers.

If you are independent, you may be involved in the problem of serialization.

For example, consider that the XML serialization of both WCF and ASP. XML Web service cannot handle circular references. Also, if you use the domain model, you will find that each customer object has multiple order objects, and each order object corresponds to a customer object. Circular references are common in complex domain models.

Circular references:

Circular references are two objects referencing each other, and each object has a property of the other type, which creates a circular reference. This is the situation below.

Code


public class Order
{

public string Orderseqno
{
Get
Set
}
Public Customer Customer
{
Get
Set
}
}



public class Customer
{
Public list<order> Orders
{
Get
Set
}
}

DTOs can help you avoid this risk and make your system more uncluttered. However, it is also introduced and new to the complexity level. We need an extra layer, a DTO adaptation layer.

3.2 Data transfer objects and service tiers

When you discuss DTOs at the beginning of the architecture meeting, you often hear voices opposing the use of DTOs. Data transfer objects can waste development time and resources. The problem is that the presence of DTOs has his necessity. They can be used without them, but they still play an important role in the enterprise architecture.

In theory, we advocate the use of DTOs when communication occurs between two tiers, including communication between the presentation layer and the service layer. In addition, we also advocate the use of different dtos, even different DTO requests and corresponding in every distinct user interface.

In actual use, things may be different. DTOs mean adding a new layer of code at the service layer, which comes with complexity. As long as there is no better choice, it is acceptable to do so. It's easy to underestimate the cost of a dto when we emphasize the cost of it. When you have hundreds of domain objects, 2-3 times the class will cause nightmares.

The benefits of using DTOs are obvious, and the need is obvious when using DTOs, otherwise the domain object is used directly.

Using DTOs We also need an internal, project-specific ORM layer.

For the ORM layer, we have many tools to choose from, commercial and open source. WCF and ASP. XML Web service generates DTOS when serializing data, but they provide limited functionality for data format control. With [XmlIgnore] in the [Ignoredatamember] and ASP. NET XML Web service in WCF, you can remove some properties from the DTO, that is, there are no such attributes in the Dto object. However, you do not have a way to automatically generate a particular DTO when the request and the corresponding classes are required, or when different user interfaces use different DTOs. So far, there is no such wizard. We need to do it manually and define the DTO ourselves.

4 Adapter Mode

When you use a DTO in a layered system, you may adjust the domain model for different interfaces. You need to implement the adapter mode, a classic and very popular mode. The essence of the adapter is to transform the interface of one class into another interface that the user wants.

4.1 Motives for using adapter mode

The role of the adapter is to represent the data in a different format. For example, the adapter converts a bit-formatted column from a database to a Boolean in the user interface for ease of use.

In a layered scenario, the adapter pattern is used to convert a domain object to a Dto object, or vice versa. There is no complex logic in the adapter class, but you need some adapter classes to assign a Dto object.

4.2 Adapter mode and service tier

Configuring an adapter class for each DTO will inevitably increase the cost of development.

When evaluating DTOs, you should continue to consider maintaining their problems for a large drop class that will be generated. You need to remember that in each adapter class, there are two functions, one from the domain object to the DTO, and one from the DTO to the domain object.

Service tiers in a tiered architecture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.