잊지 않겠습니다.

Windows Communication Foundation was official released with .NET 3.0 a couple of months ago. For those people who're doing connected, distributed systems or are in any way interested in communication aspects of systems, this ought to be a God-send. WCF basically rolled all the different Microsoft messaging formats into one, making it extremely easy to architect the communication layer of simple to complex applications. This tutorial aims to explain the basic concepts behind the common terminology used in WCF development and design.

Below is a quick overview of the WCF architecture


WCF Programs

WCF programs are basically divided into 3 different types of programs. They are common known as

  • Clients
    Clients are program that consumes the services, they are normally the ones that initiate the messenging to the service. Depending on the designed architecture of your application, it is possible that a service behaves as a client as well.
  • Services
    Services are the programs that offers the services to the consumers. They are the ones that react and process the messages, similar to the backend of the application. They can be viewed as the equivalence of web services in .Net 2.0.

    All services have to have endpoints specified in order to work. A good way to remember proper endpoint configurations is ABC. A being Address, B being Binding and C being Contracts

    • Address
      Address are the expose points of services. Services have to tell the world that where they are via addresses.
    • Bindings
      Bindings will describe to the world on how they will communicate with the world. They contain information such as transport way, how they are encoded, are they reliable etc.
    • Contracts are of (but not necessary all have to be present) 3 different kinds

      • Service Contract
        Describes what the service does.
      • Data Contract
        Define custom messaging structure.
      • Message Contract
        Define the message format that is passed between services.

  • Intermediaries
    Intermediaries are programs that act as "middle-man", their basic roles can be similar to providing a firewall, routing, gateway etc. They are commonly invisible to the client and services.

Messages
All services and clients communicate via messages, which are made up of one body, and one or more header. All WCF messages are XML formatted and transport neutral. In other words, you can specify different forms of transport (HTTP, MSMQ, Named Pipes etc) for different messages. Within each application, you can specify different messaging transport depending on the communication needs of the system. Basically, messages can be divided into

  • Simplex
    One way messaging. Simplex in short means "fire and forget"
  • Duplex
    Asynchronous two-way messaging. In short this means that once fired, the application will carry on doing its own thing. Upon the return results, it will then handle it.
  • Request Reply
    Synchronous 2 way messaging. This is the common communicate method whereby you'll fire a request, and wait for the response before continuing.

 

Channels
Before a client and service can talk to each other, they have to go through a channel. Imagine a channel as a pipe, with one end being the input message and the other end with the results of the message. There're different channels that can be stacked onto each other, they are commonly known as Channel Stacks. They can be of these different types:

  • Reliable Sessions
  • TCP Transport
  • Binary Message Encoder
  • Windows Security
  • Request Reply

 The way in which messages are sent through the pipe (Channel) is known as a Transport and they way at which they are encoded are known as Encodings. Transport can be made up of the following:

  • HTTP
  • TCP
  • MSMQ
  • Named Pipes
Posted by Y2K
,

WCF Architecture

.NET Framework 2009. 1. 7. 11:28
Figure 1 illustrates the generic architecture WCF employs for all services.

Figure 1 - General WCF Architecture

Figure 1 - General WCF Architecture

The outer service represents the AppDomain of the service. A WCF service consists of contracts (data, fault and service contracts), a service instance (implementation) which is the implementation of a service contract, and configuration which contains the service endpoint information used at runtime to create the channel stack and the service instance.

A WCF service endpoint consists of two core elements: the service contract and a binding. A binding describes how the service will communicate with clients at runtime. WCF provides several default bindings out of the box, covering many common communication scenarios such as BasicHttpBinding and MsmqIntegrationBinding. In addition to creating bindings from scratch, you can also extend and customize the default bindings to work as you wish.

Service Instancing and opening communication

Figure 1 illustrates what happens when a WCF service is run. Ultimately, the aim of the service is to map messages from clients to operations within the service instance. The service instance requires a runtime host and the host must be opened for communication to occur. The ServiceHost<T> class represents this host in code. When the host's constructor is run, it uses the service endpoint configuration combined with the contracts defined in assemblies (retrieved using reflection) to create a ServiceDescription. Thus, the Service host description contains the complete description of the service, including what contracts to use, what service implementation to use for the service contract and how the service will communicate with the outside world (binding).

When the ServiceHost<T>.Open() method is run the Service Description is used to create a Channel Stack and a Service Instance. The Channel Stack is the runtime equivalent of the Binding information. The stack contains all the protocols required in order for the communication. As a minimum for any binding, this must contain at least a Transport and an Encoding. Additional protocols (such as Sessions and Transactions) can then be applied on top. For more information on the channel stack architecture, look at the following MSDN article: http://msdn2.microsoft.com/en-us/library/ms729840.aspx.

Once the service host is open, the service is ready to receive incoming requests from a client. The inbound message gets received through the channel stack and the Dispatcher is then responsible for assigning the message to the corresponding Service Instance operation, deserializing the message using the appropriate deserializer and executing the operation on the service instance. For more information on serialization , look at the following blog entry:http://blogs.conchango.com/simonevans/archive/2007/05/14/WCF-serialization-with-MSMQ.aspx.

Behaviors in WCF

Behaviors are a way of changing the default way in which either a service instance, or operation will execute when run. Behaviors either inherit from interface IServiceBehavior or IOperationBehavior. They are attached to the service description when the host is constructed, using a mixture of configuration, and/ or any additional code you choose to add. Whether you add a behavior in code or in configuration depends on whether you want the behavior to be configurable, or if you need to behavior to be permanently applied.

Examining runtime metadata using InstanceContext and OperationContext

Whilst the service instance is running, the InstanceContext class provides you with the ability to examine metadata about the instance at runtime, such as information about the channel stack and the host. The lifetime of the InstanceContext is aligned to the life time of the service instance. Likewise, the OperationContext provides you with runtime access to service operation metadata for the lifetime of the call to the service operation. OperationContext provides you with access to information such as message headers and properties for inbound and outbound messages, and the Dispatcher.

Handling Concurrency

InstanceContextMode and ConcurrencyMode are service behavior attributes applied to the Service Description when the host is constructed. Together, these two attributes are used to configure how a service will control the lifetime of service instances and how many messages a dispatcher will hand over to an instance.

The InstanceContextMode controls the lifetime of a service instance. By default, this is set to PerSession. This means the service instance will last for the lifetime of the corresponding Session (which equals PerCall if no session is available). PerCall instancing means the instance will be destroyed after the service operation completes. The final option here is Single, which means that the instance context will only be destroyed when the host is closed.

The ConcurrencyMode handles how many messages the dispatcher will hand over to the service instance. The default isSingle, which means the service instance runs single threaded, but this can be changed to run multi threaded by using the setting Multi.

Additional to InstanceContextMode and ConcurrencyMode, the ServiceThrottlingBehavior controls how many concurrent service instances will be run by the host at one time (the MaxConcurrentInstances property), and how many concurrent calls can be made to a single instance (the MaxConcurrentCalls property). It is worth noting with this final property that the channel stack will automatically ready the next inbound message even when concurrent calls are set to 1.

All of these behaviors together control how concurrency and threading will be handled within a WCF service. Figures 2 to 4 below show how these variables can affect threading and concurrency in WCF.

Figure 2

Figure 2 – PerCall instancing, Single Threaded with 2 concurrent instances

Figure 2 shows a service that allows two concurrent service instances to run, each of which is destroyed when the call to the operation is complete (PerCall). Each service instance is configured to only allow one thread to run at a time. This means that of the three inbound messages (shown on the left), the dispatcher will handle two currently using two service instances in the process. The third message will be made ready by the channel stack for handling by the dispatcher.

Figure 3

Figure 3 – PerCall instancing, Single Threaded with 1 concurrent instance

Figure 3 shows what happens when the concurrent instances property is set to 1. The result is only one service instance is created and runs single threaded. A second message is made ready for the dispatcher in the channel stack and is not processed until the service instance is destroyed at the end of the first operation call.

Figure 4

Figure 4 - Single Instance, Multi threaded with 2 concurrent calls

Figure 4 shows how using multi threaded concurrency with a single instance would affect how the service behaves with two concurrent calls allowed. The top two inbound messages from the channel stack would make a call to an operation on a single service instance concurrently. This service instance would not be destroyed at the end of the call to the operation. The third message would be waiting in the channel stack, and as soon as the service instance made a thread free for use, the dispatcher will call the operation for the third message against the same service instance.

Service Exceptions

When a service instance throws an unhandled exception, the InstanceContext is said to be in a Faulted state, and theFaulted event will be raised. This event can be handled in the service host. Once the host is in a faulted state, no further service instances will be created until the channel stack is taken out of a faulted state. This can be achieved by closing and reopening the host (services hosted in IIS automatically handled restarting the host).

Posted by Y2K
,

Service End Point

Host application(Service)은 클라이언트가 요청을 보낼 수 있는 End-Point를 제공함으로서 클라이언트 어플리케이션이 사용할 수 있는 서비스를 만든다.

Service Address

선택된 전송기법에 맞게 주소를 명시해야지 된다.

Service Binding

Service Binding에서는 서비스와 연결하는 방식과 서비스가 제공하는 데이터 포멧을 나타낸다.

  • 전송 프로토콜 : IIS의 지원시에는 전송프로토콜로 Http, Https를 설정, TCP 등의 전송 스킴에 대한 주소의 명세화
  • 메세지 엔트포인트 포멧 : 일반적으로 XML형태로 데이터 전송, 특별한 image등의 데이터를 보낼때는 다른 방식으로 encoding
  • 서비스 보안 요구사항 : 전송 레벨과 메세지 레벨에서의 보안의 구현
  • 서비스 트랜젝션 요구사항 : 트랜잭션 서비스의 구현
  • 서비스 커뮤니케이션의 신뢰성 : 데이터 교환의 무결성 확인
Service가 구현하는 계약

[ServiceContract] 속성의 인터페이스 구현

[OperationContract]의 동작에 대한 구현 : 반드시 직렬화가 가능한 형태로 만들어질 수 있어야지 된다.

  

Client process

WCF Runtime에서 보안, 신뢰성, 트랜젝션을 만족하는지에 대한 확인에 대한 채널 객체의 컬랙션 제공

WCF Runtime에서는 Channel과 Service Instance간의 연결 방법을 명시할 수 있다. 이는 서비스 계약을 구현한 Class에 [ServiceBehavior] 속성을 추가하는 것으로 WCF Runtime이 서비스를 초기화하는 방식을 수정할 수 있다. 

  • InstanceContextMode.PerCall : Method를 호출할 때마다 서비스의 새로운 Instance가 호출된다.
  • InstanceContextMode.PerSession : Session을 구현하면, Client의 Session별로 Instance가 생성된다. Session이 만료되면 Instance는 제거가 되며, Session이 유지되고 있는 도중에는 Instance는 계속 유지가 된다.
  • InstanceContextMode.Single : Service의 Instance는 하나만이 생성되며, 모든 client와 Session은 하나의 Instance에 의해서 공유가 되게 된다.
  [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
  public class ProductServiceImpl : IProduct

  

WCF Service Hosting

  • IIS를 이용 WebService를 이용한 WCF Service Hosting
  • Window Service를 이용한 WCF Service hosting
  • IIS 7.0을 이용한 Windows Activate Service(WAS) 이용
Posted by Y2K
,