Wednesday, 15 April 2015

Dependency Inversion Principle, Inversion of Control (IOC) and Dependency Injection

Introduction

In this article we will talk about the Dependency Inversion Principle, Inversion of Control and Dependency Injection. We will start by looking at the dependency inversion principle. We will then see how we can use inversion of control to implement dependency inversion principle and finally we will look at what dependency injection is and how can it be implemented. 

Background 

Before we start talking about Dependency Injection(DI), we first need to understand the problem that DI solves. To understand the problem, we need to know two things. First dependency Inversion Principle(DIP) and second  Inversion of Controls(IoC). let us start our discussion with DIP, then we will talk about IoC. once we have discussed these two, we will be in a better position to understand Dependency Injection, so we will look at dependency injection in details. Then finally we will discuss see how can we implement Dependency injection.

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 moduleAppPoolWatcher 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 orEmailSender.
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. theAppPoolWatcher 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. (Next we will see how this can be done)  

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.

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 ourAppPoolWatcher 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:
Hide   Copy Code
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
Hide   Copy Code
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.

Point of interest

In this article we have discussed about Dependency inversion principle(Which is the D part of SOLID object oriented principle). We have also discussed how inversion of control is used to implement dependency inversion and finally we have seen how dependency injection help in creating decoupled classes and how to implement dependency injection. This article has been written from beginner's perspective. I hope this has been informative.


Wednesday, 17 December 2014

WCF: Types of Contract

It is contracts that that client and service agree as to the type of operation and structure they will use during communication. it is a formal agreement between a client and service to define a platform-neutral and standard way of describing what the service does. WCF defines four types of contracts
·         Service Contract
·         Data Contract
·         Message Contract
·         Fault Contract  


Service Contract
Service contract describes the operations, or methods, that are available on the service endpoint, and exposed to the outside world. A Service contract describes the client-callable operations (functions) exposed by the service, apart from that it also describes.   
·         location of operations, interface and methods of your service to a platform-independent description
·         message exchange patterns that the service can have with another party. might be one-way/request-reply/duplex.
To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface/class with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with theOperationContract Attribute.   
 Collapse | Copy Code
[ServiceContract]
interface ICuboidService
{
    [OperationContract]
    CuboidDetail CalculateDetails2(CuboidInfo cInfo);
}

Data Contract
In one line, data contract describes the data to be exchanged. it is formal agreement between service and client, that contains information about the data they will be exchanging. the important point, which needs to be mentioned here is that the two parties don’t have to share the same data types to communicate, they only need the share the same data contracts. Data contract defines which parameter & return type will be serialized/de-serialized to and from (Binary <==> XML) in order to be transmitted between one party to another.  Data contracts can be defined by annotating a class, enumeration, or even a structure, but not an interface. 
To define a data contract, you simply decorate a class or enumeration with [DataContract] attribute, as shown below.  
 Collapse | Copy Code
[DataContract]
public class CuboidInfo
{
}

Message Contract
WCF uses SOAP message for communication. Most of the time developer concentrates more on developing theDataContract, Serializing the data, etc. Some time developer will also require control over the SOAP message format. In that case WCF provides Message Contract to customize the message as per requirement. 
A Message Contract is used to control the structure of a message body and serialization process. It is also used to send / access information in SOAP headers. By default WCF takes care of creating SOAP messages 
according to service
 DataContracts and OperationContracts
So when you need full control on SOAP messages structure and how serialization happens specially when your service needs to be interoperable for consuming by different types of clients or service needs to provide extra layer of security on messages and message parts, Amessage is nothing but a packet and WCF uses this packet to transfer information from source to destination. This message contains an envelope, header and body. There are some rules, which one needs to follow, while working with  message contract.
·         When using Message contract type as parameter, Only one parameter can be used in Operation.
·         Service operation either should return MessageContract type or it should not return any value.
·         Operation will accept and return only message contract type. Other data types are not allowed.




Choosing between DataContract and MessageContract. 
90% of the time, DataContract will be sufficient, You'll only need message contracts if you need to very closely and very specifically control the layout of your SOAP messages. In most of the time,  you don't need to.    
A message contract allows you to specifically say which elements (scalar types or compound types asDataContracts) will be in the SOAP header, and which will be in the SOAP body.  
You might need this if you have a communication partner, with whom you have agreed to a very specific format and you have to tweak your SOAP messages to match that given layout exactly. That's just about the only valid scenario when you'll need to and should use message contracts.
However, sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.   
So, to making the long story short: always use data contracts, practically never use message contracts (unless you really have to).    

Fault Contract
Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has occurred, and where. By default when we throw any exception from service, it will not reach the client side. The less the client knows about what happened on the server side, the more dissociated the interaction will be, this phenomenon (not allowing the actual cause of error to reach client). is known as error masking. By default all exceptions thrown on the service side always reach the client as FaultException, as by having all service exceptions indistinguishable from one another, WCF decouples the client from service.  
While the default policy of error-masking is best practice of WCF, but there are times when client is required to respond to these exceptions in a prescribed and meaningful way. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.  SOAP faults are based on industry standard that is independent of any technology specific exceptions, it is a way to map technology specific exceptions to some neutral error information. So when service meets as unexpected error, instead of throwing a raw CLR exception (technology specific), service can throw an instance of the FaultException <T> class.  


WCF : Data Contracts Vs Message Contracts

1. Comparison

Data Contracts

WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.
you can say “Data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged”. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Message Contracts

Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP.
Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

2. Why use MessageContract when DataContract is there?

Data contracts are used to define the data structure. Messages that are simply a .NET type, lets say in form of POCO (plain old CLR object), and generate the XML for the data you want to pass.
Message contracts are preferred only when there is a need to “control” the layout of your message(the SOAP message); for instance, adding specific headers/footer/etc to a message.
Sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.

3. Why we use MessageContract to pass SOAP headers ?

Passing information in SOAP headers is useful if you want to communicate information “out of band” from the operation signature.
For instance, session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself.
Another example is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.
A third example, again with security, is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.

4. Can’t mix datacontracts and messagecontracts.

Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it return a MessageContract, or specify a MessageContract as the input argument to an operation and have it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service.
Hope this will help !!!