Wednesday, August 13, 2014

Why layer a service?

An important aspect of SOA design is that service boundaries should be explicit, which means hiding all the details of the implementation behind the service boundary. This includes revealing or dictating what particular technology was used.
Furthermore, inside the implementation of a service, the code responsible for the data manipulation should be separated from the code responsible for the business logic. So in the real world, it is always good practice to implement a WCF service in three or more layers. The three layers are the service interface layer, the business logic layer, and the data access layer.

  • Service interface layer: This layer will include the service contracts and operation contracts that are used to define the service interfaces that will be exposed at the service boundary. Data contracts are also defined to pass in and out of the service. If any exception is expected to be thrown outside of the service, then Fault contracts will also be defined at this layer.
  • Business logic layer: This layer will apply the actual business logic to the service operations. It will check the preconditions of each operation, perform business activities, and return any necessary results to the caller of the service.
  • Data access layer: This layer will take care of all of the tasks needed to access the underlying databases. It will use a specific data adapter to query and update the databases. This layer will handle connections to databases, transaction processing, and concurrency controlling. Neither the service interface layer nor the business logic layer needs to worry about these things.

  • Layering provides separation of concerns and better factoring of code, which gives you better maintainability and the ability to split out layers into separate physical tiers for scalability. The data access code should be separated into its own layer that focuses on performing translation services between the databases and the application domain. Services should be placed in a separate service layer that focuses on performing translation services between the service-oriented external world and the application domain.

    The service interface layer will be compiled into a separate class assembly and hosted in a service host environment. The outside world will only know about and have access to this layer. Whenever a request is received by the service interface layer, the request will be dispatched to the business logic layer, and the business logic layer will get the actual work done. If any database support is needed by the business logic layer, it will always go through the data access layer.

    What is WCF?

    Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

    WCF makes the development of endpoints easier.It is designed to offer a manageable approach to creating Web services and Web service clients.


    WCF includes the following set of features.
    • Service Orientation
      One consequence of using WS standards is that WCF enables you to create service oriented applications. Service-oriented architecture (SOA) is the reliance on Web services to send and receive data. The services have the general advantage of being loosely-coupled instead of hard-coded from one application to another. A loosely-coupled relationship implies that any client created on any platform can connect to any service as long as the essential contracts are met.
    • Interoperability
      WCF implements modern industry standards for Web service interoperability.
    • Multiple Message Patterns
      Messages are exchanged in one of several patterns. The most common pattern is the request/reply pattern, where one endpoint requests data from a second endpoint. The second endpoint replies. There are other patterns such as a one-way message in which a single endpoint sends a message without any expectation of a reply. A more complex pattern is the duplex exchange pattern where two endpoints establish a connection and send data back and forth, similar to an instant messaging program.
    • Service Metadata
      WCF supports publishing service metadata using formats specified in industry standards such as WSDL, XML Schema and WS-Policy. This metadata can be used to automatically generate and configure clients for accessing WCF services. Metadata can be published over HTTP and HTTPS or using the Web Service Metadata Exchange standard.
    • Data Contracts
      Because WCF is built using the .NET Framework, it also includes code-friendly methods of supplying the contracts you want to enforce. One of the universal types of contracts is the data contract. In essence, as you code your service using Visual C# or Visual Basic, the easiest way to handle data is by creating classes that represent a data entity with properties that belong to the data entity. WCF includes a comprehensive system for working with data in this easy manner. Once you have created the classes that represent data, your service automatically generates the metadata that allows clients to comply with the data types you have designed.
    • Security
      Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-SecureConversation.
    • Multiple Transports and Encodings
      Messages can be sent on any of several built-in transport protocols and encodings. The most common protocol and encoding is to send text encoded SOAP messages using is the HyperText Transfer Protocol (HTTP) for use on the World Wide Web. Alternatively, WCF allows you to send messages over TCP, named pipes, or MSMQ. These messages can be encoded as text or using an optimized binary format. Binary data can be sent efficiently using the MTOM standard. If none of the provided transports or encodings suit your needs you can create your own custom transport or encoding.
    • Reliable and Queued Messages
      WCF supports reliable message exchange using reliable sessions implemented over WS-Reliable Messaging and using MSMQ.
    • Durable Messages
      A durable message is one that is never lost due to a disruption in the communication. The messages in a durable message pattern are always saved to a database. If a disruption occurs, the database allows you to resume the message exchange when the connection is restored. You can also create a durable message using the Windows Workflow Foundation (WF).
    • Transactions
      WCF also supports transactions using one of three transaction models: WS-AtomicTtransactions, the APIs in the System.Transactions namespace, and Microsoft Distributed Transaction Coordinator.
    • AJAX and REST Support
      REST is an example of an evolving Web 2.0 technology. WCF can be configured to process "plain" XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard), and even non-XML formats, such as JavaScript Object Notation (JSON).
    • Extensibility
      The WCF architecture has a number of extensibility points. If extra capability is required, there are a number of entry points that allow you to customize the behavior of a service.

    Wednesday, August 6, 2014

    Dependency Injection

    Now that we know the dependency inversion principle and have seen the inversion of control methodology for implementing the dependency inversion principle, Dependency Injection is mainly for injecting the concrete implementation into a class that is using abstraction i.e. interface inside. The main idea of dependency injection is to reduce the coupling between classes and move the binding of abstraction and concrete implementation out of the dependent class.
    Dependency injection can be done in three ways.
    1. Constructor injection
    2. Method injection
    3. Property injection

    Constructor Injection 


    In this approach we pass the object of the concrete class into the constructor of the dependent class. So what we need to do to implement this is to have a constructor in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        public AppPoolWatcher(INofificationAction concreteImplementation)
        {
            this.action = concreteImplementation;
        }
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {   
            action.ActOnNotification(message);
        }
    }
    
    In the above code, the constructor will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do is

    EventLogWriter writer = new EventLogWriter();
    AppPoolWatcher watcher = new AppPoolWatcher(writer);
    watcher.Notify("Sample message to log");
    
    Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher's constructor. This method is useful when we know that the instance of the dependent class will use the same concrete class for its entire lifetime.

    Method Injection


    In constructor injection we saw that the dependent class will use the same concrete class for its entire lifetime. Now if we need to pass separate concrete class on each invocation of the method, we have to pass the dependency in the method only.

    So in method injection approach we pass the object of the concrete class into the method the dependent class which is actually invoking the action. So what we need to do to implement this is to have the action function also accept an argument for the concrete class object and assign it to the interface handle this class is using and invoke the action. So if we need to implement this for our AppPoolWatcher class:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        // This function will be called when the app pool has problem
        public void Notify(INofificationAction concreteAction, string message)
        {
            this.action = concreteAction;
            action.ActOnNotification(message);
        }
    }
    
    In the above code the action method i.e. Notify will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do is

    EventLogWriter writer = new EventLogWriter();
    AppPoolWatcher watcher = new AppPoolWatcher();
    watcher.Notify(writer, "Sample message to log");
    
    Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher's invocation method i.e. Notify method in the above example. 

    Property Injection


    Now we have discussed two scenarios where in constructor injection we knew that the dependent class will use one concrete class for the entire lifetime. The second approach is to use the method injection where we can pass the concrete class object in the action method itself. But what if the responsibility of selection of concrete class and invocation of method are in separate places. In such cases we need property injection.

    So in this approach we pass the object of the concrete class via a setter property that was exposed by the dependent class. So what we need to do to implement this is to have a Setter property or function in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        public INofificationAction Action
        {
            get
            {
                return action;
            }
            set
            {
                action = value;
            }
        }
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {   
            action.ActOnNotification(message);
        }
    }
    
    In the above code the setter of Action property will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do is

    EventLogWriter writer = new EventLogWriter();
    AppPoolWatcher watcher = new AppPoolWatcher();
    // This can be done in some class
    watcher.Action = writer;
    
    // This can be done in some other class
    watcher.Notify("Sample message to log");
    
    Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the setter exposed by AppPoolWatcher class. This approach is useful when the responsibility of selecting the concrete implementation and invoking the action are done in separate places/modules. 

    In languages where properties are not supported, there is a separate function to set the dependency. This approach is also known as setter injection. The important thing to note in this approach is that there is a possibility that someone has created the dependent class but no one has set the concrete class dependency yet. If we try to invoke the action in such cases then we should have either some default dependency mapped to the dependent class or have some mechanism to ensure that application will behave properly.

    A Note on IoC Containers


    Constructor injection is the mostly used approach when it comes to implementing the dependency injection. If we need to pass different dependencies on every method call then we use method injection. Property injection is used less frequently.

    All the three approaches we have discussed for dependency injection are ok if we have only one level of dependency. But what if the concrete classes are also dependent of some other abstractions. So if we have chained and nested dependencies, implementing dependency injection will become quite complicated. That is where we can use IoC containers. IoC containers will help us to map the dependencies easily when we have chained or nested dependencies.


    What is Inversion of Control?

    Dependency inversion was a software design principle, it just states that how two modules should depend on each other. Now the question comes, how exactly we are going to do it? The answer is Inversion of control. Inversion of control is the actual mechanism using which we can make the higher level modules to depend on abstractions rather than concrete implementation of lower level modules.
    So if I have to implement inversion of control in the above mentioned problem scenario, the first thing we need to do is to create an abstraction that the higher levels will depend on. So let us create an interface that will provide the abstraction to act on the notification received from AppPoolWacther.

    public interface INofificationAction
    {
        public void ActOnNotification(string message);
    }
    
    
    Now let us change our higher level module i.e. the AppPoolWatcher to use this abstraction rather than the lower level concrete class.
    
    
    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {
            if (action == null)
            {
                // Here we will map the abstraction i.e. interface to concrete class 
            }
            action.ActOnNotification(message);
        }
    }
    
    So how will our lower level concrete class will change? how will this class conform to the abstraction i.e. we need to implement the above interface in this class:
     
    class EventLogWriter : INofificationAction
    {   
        public void ActOnNotification(string message)
        {
            // Write to event log here
        }
    }

    So now if I need to have the concrete classes for sending email and sms, these classes will also implement the same interface.

    class EmailSender : INofificationAction
    {
        public void ActOnNotification(string message)
        {
            // Send email from here
        }
    }
    
    class SMSSender : INofificationAction
    {
        public void ActOnNotification(string message)
        {
            // Send SMS from here
        }
    }
    
    So the final class design will look like: 


    So what we have done here is that, we have inverted the control to conform to dependency inversion principle. Now our high level modules are dependent only on abstractions and not the lower level concrete implementations, which is exactly what dependency inversion principle states.
    But there is still one missing piece. When we look at the code of our AppPoolWatcher, we can see that it is using the abstraction i.e. interface but where exactly are we creating the concrete type and assigning it to this abstraction. To solve this problem, we can do something like:

    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        INofificationAction action = null;
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {
            if (action == null)
            {
                // Here we will map the abstraction i.e. interface to concrete class 
                writer = new EventLogWriter();
            }
            action.ActOnNotification(message);
        }
    }
    
    But we are again back to where we have started. The concrete class creation is still inside the higher level class. Can we not make it totally decoupled so that even if we add new classes derived from INotificationAction, we don't have to change this class. 

    This is exactly where Dependency injection comes in picture. So its time to look at dependency injection in detail now.

    What is Dependency Inversion Principle?

    Dependency inversion principle is a software design principle which provides us the guidelines to write loosely coupled classes. According to the definition of Dependency inversion principle:
    1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    2. Abstractions should not depend upon details. Details should depend upon abstractions.

    What does this definition mean? What is it trying to convey? let us try to understand the definition by looking at examples. A few years back I was involved in writing a windows service which was supposed to run on a Web server. The sole responsibility of this service was to log messages in event logs whenever there is some problem in the IIS application Pool. So what our team has done initially that we created two classes. One for monitoring the Application Pool and second to write the messages in the event log. Our classes looked like this:


    class EventLogWriter
    {
        public void Write(string message)
        {
            //Write to event log here
        }
    }
    
    class AppPoolWatcher
    {
        // Handle to EventLog writer to write to the logs
        EventLogWriter writer = null;
    
        // This function will be called when the app pool has problem
        public void Notify(string message)
        {
            if (writer == null)
            {
                writer = new EventLogWriter();
            }
            writer.Write(message);
        }
    }
    
    
    From the first look, the above class design seems to be sufficient. It looks perfectly good code. But there is a problem in the above design. This design violates the dependency inversion principle. i.e. the high level module AppPoolWatcher depends on EventLogWriter which is a concrete class and not an abstraction. How is it a problem? Well let me tell you the next requirement we received for this service and the problem will become very clearly visible.
    The next requirement we received for this service was to send email to network administrator's email ID for some specific set of error. Now, how will we do that? One idea is to create a class for sending emails and keeping its handle in the AppPoolWatcher but at any moment we will be using only one object either EventLogWriter or EmailSender.
    The problem will get even worse when we have more actions to take selectively, like sending SMS. Then we will have to have one more class whose instance will be kept inside the AppPoolWatcher. The dependency inversion principle says that we need to decouple this system in such a way that the higher level modules i.e. the AppPoolWatcher in our case will depend on a simple abstraction and will use it. This abstraction will in turn will be mapped to some concrete class which will perform the actual operation.