Friday, March 29, 2013

Design Pattern: .NET DI (IoC) Frameworks


Having some spare time and interest, I decided to learn a bit more about the features of modern .NET IoC frameworks. Being aware of what’s available always helps, and I haven’t yet seen a comprehensive feature comparison.
For the comparison, I have selected the frameworks that I feel to be most documented and popular:
If you feel that your framework should be here, just send me the values for all feature columns, and I’ll add it.

0. Terminology

The first thing I learned is that common concepts are sometimes named differently between the frameworks.
So I think it makes sense to start with some terminology.
Components are classes registered within the container. They can be instantiated by the container to satisfy servicedependencies of other components. Services are what components provides and depends on.
In most of the cases services are interfaces, and components are classes implementing them.
Autowiring is an automatic detection of dependency injection points. If the framework is able to  match the constructor parameter types with registered services and provide these services, it is an example of autowiring.
Transient components, as compared to singletons, are created each time they are requested from container. The exact term used for transients differs quite much between frameworks.
Automatic registration is a way to automatically detect and register components within an assembly (or larger environment). It can also be called batch registration.

1. Licensing and core size

All reviewed frameworks work under .NET 2.0, and have liberal licenses allowing commercial and open-source usage.
The first table lists the reviewed frameworks with some basic parameters.
The color map is easy: green is great, yellow is ok, red is bad. All colors are extremely subjective, things bad for me may mean that I am doing something wrong.
I do not feel library count or size to be important for developments, so no red points this time.
Ninject is the most interesting case, since it has a very naive auto-wiring implementation by default. However, it has an official Ninject.Extensions.AutoWiring library, so in all following tables I included its features in Ninject functionality.

2. Container configuration

The first thing to do with container is to register something in it. So let’s review the configuration options provided by various framework.
As you can see, all frameworks support programmatic registration. Even better, most of them have fluent interfaces for registration API. Spring.Net and Castle are behind others in this regard, since Spring.Net API is somewhat cumbersome and not fluent, while Castle does not support fluent registration in RC3.
As I noted before, automatic registration is a way to register all types in given set of assemblies/namespaces based on attributes or other conventions. I find it very useful, since the convention-driven approach saves time on configuration and lessens a chance of a configuration error.
Castle’s BatchRegistrationFacility is obsolete and well-hidden, also it uses GetExportedTypes instead of GetTypes (The Sin of Shallow Digging), so it’s useless if you want to hide implementations and expose only interfaces. For Spring.NET I didn’t find an easy way, but it still might be possible, so you can correct me on this one.
Some people consider attributes to be POCO, some not, and I tend to agree with the latter when we are talking about DI frameworks. So no red points or yellow points if framework has no attributes, this column just for your information.
As for XML, I have a very strong opinion — only if actually needed, only as much as actually needed. Fortunately, no one of reviewed frameworks required XML (while most of them support it when needed). Spring.Net is somewhat differently oriented for this question, since its XML API is a better, more documented and encouraged approach. However, since Spring is a Java port, the approach is probably a compatibility heritage.

3. Basic injection/autowiring

The second thing after configuring the framework is knowing what exactly can be automatically injected. And, as I explained earlier, autowiring is just a name for framework-discovered injection points.
Basic constructor injection works great in all frameworks. For property injection Unity and StructureMap require explicit opt-in and treat the dependency as mandatory, which is a bit counterintuitive and does not provide any benefit over constructor injection.
As for multiple constructors, I really like the Castle/Autofac choice of constructor with most resolvable parameters. This is precisely what the human programmer will do, given a number of constructors and dependencies. With approach taken by Unity and StructureMap, it is harder to keep object DI-ignorant — you have to think whether your most-parameter constructor is resolvable, add DI-specific attributes or specify the constructor explicitly in the XML/code configuration.
The most interesting behavior was shown by the Spring.Net — it selected default (no-parameter) constructor first, and only if default did not exists, Spring went to the most resolvable.
Recursive dependency resolution is, in my opinion, one of the most important things in a DI framework. In a large project, when you have a lot of components and services, solving recursion easily is a must. In my tests only Castle and Autofac gave a useful error message, all other frameworks just crashed with unrecoverable StackOverflowException, which is a bad, bad thing to get in automatic test runner.

Design Pattern: IOC and DI part 2

What is Inversion of Control?

According to Wikipedia “Inversion of Control, or IoC, is an abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming”.
The latter part of that quote is interesting. According to it Inversion of Control is a way to invert the flow of control in comparison to procedural programming.
What that means is that in procedural programming a chunk of code that uses, or consumes, another chunk of code is in control of the process.
It knows exactly what piece of code, what method in what class, it uses. And in doing so it is also quite likely that it knows about some implementation details in the code it uses.

An example

One example of such a scenario and of such a dependency is when a class, illustrated as X below, uses another class Y.

The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?
Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?
By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.

In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.
That could be Y, but it could also be A, B or C given that they implement I. Of course this discussion is rather abstract at the moment, but we’ll get to how to implement this in a second using either Dependency Injection or Service Locator.
For now, let’s just assume that we can and that we can change what implementation of I X uses at runtime. What benefits can we get from that?

Benefits of Inversion of Control

Well, first of all X is not dependent on Y anymore and it’s therefore less likely that we’ll have to make changes to X when we make changes in Y as we’re less likely to write code in X that relies on implementation details in Y.
Furthermore X is now much more flexible as we can change which implementation of I it uses without changing anything in X.
Perhaps Y is a component for sending e-mails and we want X, who used to send e-mails, to start sending tweets instead using Z who also implements I. Since X no longer relies specifically on Y but on something that implements I we don’t have to modify anything in X.
Another benefit of inversion of control is also that we can isolate our code when creating unit tests.
Suppose, as before, that X used Y to send messages which Y did in the form of e-mails using an SMTP-server. When creating unit test, which should only test a single unit of code, we want to be able to test the logic in X without having to care about the component that sends messages, and we most definitely don’t want our tests to fail because Y doesn’t have access to an SMTP server.
Having used inversion of control X doesn’t rely on Y anymore but on an implementation of I that just happens to be Y.
That means that we, in the setup phase of our tests, can change it so that X uses a different implementation of I, such as a mock object which doesn’t send any messages at all, and which also allows us to check that X has used it in a correct way.

Applying Inversion of Control – A sample scenario

Enough with the X and the Y and I! Let’s look at a more concrete scenario.
We have a class named OrderService which is used for processing orders.
It has a method named AcceptOrder which receives an Order object, validates that it is valid according to the business rules (it may for instance check that the order’s shipping address is a valid address and that there are enough items in stock) and then, given that the order is valid, saves it to a database using another class named OrderDatabase.

The code for OrderService looks like this:
public class OrderService
{
    public void AcceptOrder(Order order)
    {
        //Domain logic such as validation

        new OrderDatabase().SaveOrder(order);
    }
}
Notice line seven above where AcceptOrder creates a new instance of the OrderDatabase class and then saves the order using it’s SaveOrder method. This might not be the most realistic scenario. In the real world SaveOrder could be static, making line seven in the example look like this:
OrderDatabase.SaveOrder(order);
Or there might a singleton implementation of OrderDatabase making line seven look like this:
OrderDatabase.Instance.SaveOrder(order);
Either way it doesn’t matter. What matters is that AcceptOrder relies on OrderDatabase which is something very concrete.
How OrderDatabase is implemented isn’t very important as long as we realize that relying on it is inflexible and bad for testability. For the sake of this example let’s assume it’s SaveOrder method looks like this:
public void SaveOrder(Order order)
{
    throw new ApplicationException("I need a database to work");
}
This will make it very hard to test the business logic in OrderService’s AcceptOrder method since it will call the SaveOrder method which in turn throws an exception.
To fix this we apply Inversion of Control by creating an abstract definition of the behavior in OrderDatabase that OrderService needs in the form of the interface IOrderSaver and making AcceptOrder use an instance of IOrderSaver instead of an instance of OrderDatabase.

OrderService no longer knows about the OrderDatabase class. It just uses an instance of the IOrderSaver interface of which OrderDatabase is one of possibly many implementation.
In fact we could easily change it so that OrderService instead uses a class that saves orders to XML files instead, without changing a single line of code in OrderService.
Or to a class that still saves to a database but that has been extended with logging.
Or to a composite that saves both to a database and to an XML file. Or to…

That’s all good, but how does OrderService get this instance of IOrderSaver you ask?
There would be little point in using the IOrderSaver interface if OrderService still had to know how to instantiate a concrete implementation of it, so we need a way for OrderService to get an instance of IOrderSaver at runtime without knowing about any concrete implementations.
There are a couple of ways to do that. Let’s begin by looking at Dependency Injection.

Dependency Injection

Using Dependency Injection we inject an instance of IOrderSaver into OrderService when we use it.
This could either be done using constructor injection, where we supply the instance to OrderService’s constructor, or property injection where we supply it to OrderService after it has been instantiated by setting a property on it.
In the diagram below I’ve tried to illustrate constructor injection.

Notice how OrderService has a constructor which requires an instance of IOrderSaver as a parameter. In code this could be implemented like this:
public class OrderService
{
    private IOrderSaver orderSaver;

    public OrderService(IOrderSaver orderSaver)
    {
        this.orderSaver = orderSaver;
    }

    public void AcceptOrder(Order order)
    {
        //Domain logic such as validation

        orderSaver.SaveOrder(order);
    }
}
As you can see in the example code above OrderService’s constructor requires an instance of IOrderSaver which it stores in a field. When invoked the AcceptOrder method uses this injected instance to save the order.
Should we want to be able to instantiate OrderService without supplying an IOrderSaver there is of course nothing stopping us from creating another constructor which sets the orderSaver field to a default implementation.
public OrderService()
{
    this.orderSaver = new OrderDatabase();
}
While this means that OrderService still knows about which implementation of IOrderSaver it uses when instantiated with this constructor we are still able to change what implementation it uses using the other constructor, for instance when we are creating unit tests.
I’m not saying this is a good idea, but it is possible and definitely better than not being able to change how OrderService saves orders at all.

Service Locator

While I think Dependency Injection is superior in just about any situation there is also another way to implement Inversion of Control, using a Service Locator.

In the diagram above OrderService doesn’t know about OrderDatabase but it does know about an instance of the concrete class ServiceLocator which in turn knows about OrderDatabase.
When AcceptOrder is invoked it will ask ServiceLocator for an instance of IOrderSaver which will supply one based on how we have configured it.
Using this approach OrderService could be implemented like this:
public class OrderService
{
    public void AcceptOrder(Order order)
    {
        //Domain logic such as validation

        OrderSaverFactory.GetOrderSaver().SaveOrder(order);
    }
}
A simple implementation of ServiceLocator would be to have it supply an instance of a default implementation of IOrderSaver unless we specifically tell it to supply another instance, like this:
public class ServiceLocator
{
    public static IOrderSaver OrderSaver { get; set; }

    public static IOrderSaver GetOrderSaver()
    {
        if (OrderSaver == null)
            OrderSaver = new OrderDatabase();

        return OrderSaver;
    }
}
I find the Service Locator approach to be much more messy than Dependency Injection and it makes unit tests harder to set up, but there might be a few situations where Dependency Injection may be impractical. Then it’s good to still be able to apply Inversion of Control by using Service Locator.

references:http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/

Design Pattern : IOC and DI Part 1

The problem 

Any good architecture always stands on the base that components are loosely coupled… let me stress the point truly loosely coupled. Let’s try to understand this with a scenario and how we normally approach this problem using pure object oriented way.

Consider a scenario where we have a customer class which needs to perform insert operation on database. The customer class should be customizable to save in either Sql server or oracle database. In future we should also be able to add new databases with out disturbing the customer class.

Below is what we will do. Define two classes one for SQL server and other for Oracle. Both these classes inherit from some kind of same interface ‘Idatabase’. The customer class points to this interface. So the customer class is theoretically shielded from the concrete implementation of SQL Server or oracle. But because the object creational activity needs to be done by the customer class it still needs to be aware of the concrete classes.
 



Figure: - General loosely coupled thinking
 
This is what will happen in actual implementation as shown in figure ‘Concrete classes’. The customer class will be creating objects of either oracle or SQL server depending on condition. That means the customer class is exposed to the concrete classes which defeats the purpose of interface. Any change in the database classes will lead to compiling of the customer class.
 



Figure :- Concrete classes


Creational patterns


The next thing comes in mind is creation patterns. If we can introduce a factory who takes the creational aspect of the concrete classes thus isolating the concrete classes from the customer class.

Here are the issues with factory which makes us force to think about some other solutions:-

• Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
• Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
• Factories are custom: - They are very much custom to a particular implementation.
• Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.

I will not be explaining factory pattern in case you are not aware of you can read the same in my previous article SoftArchInter1.aspx

Ok, I will show you a magic…Rather than writing those huge line of code for factory…lets go the DI way (Dependency injection).
 


Dependency Injection


Rather than writing factory pattern, how about injecting the object directly in to the customer class. So let the customer class references the interface and we should be able to inject the concrete type in to the customer class. With this the customer class does not need to use the new keyword and is complete decoupled from the concrete classes.





Figure: - Dependency injection
 
Injection can be done using containers. So basically you need to put both the classes in to the container and the container will create object and inject the same in to the other class.
 




Figure: - Containers
 
With this your customer class does not need to worry about creating objects and knowing the concrete objects.
 


Solving problem using UNITY block


Now that we know the benefit of containers we will explore unity application block which helps us to achieve dependency injection.
 


Download and installing Unity


The first step is to download the unity application block from http://msdn.microsoft.com/en-us/library/cc468366.aspx  and install the same. Depending on whether you have 2008 or 2005 the documentation will vary. For this tutorial I will be using VS 2005 because majority professionals are still using 2005.





Figure: - unity block installed
 
Once you install the block you should be able to see the same in Microsoft patterns and practices.

The first thing you need to do is to get the references of at least two components Unity and Unity configuration.
 



Figure: - Add referenced to Unity components
 
Once you have got reference to the components import the “Microsoft.Practices.Unity” namespace in to your code as shown in figure ‘Import unity namespace’.




Figure: - Import unity namespace
 

Defining the common interface


As said previously we should be able to inject SQL Server database object or oracle database object in the customer class. So as a good practice we will inherit the SQL server implementation and oracle implementation from a common interface ‘Idatabase’.
 



Figure: - Database interfaces
 

Providing the injection gateway


In the customer class we will reference the interface and expose the public property using [Dependency] attribute. This exposure is essential for the unity container. Unity container needs some kind of gateway by which it can inject the object. So what we have done is we have exposed the interface ‘iDatabase’ publicly. There are lot of other ways by which we can achieve the same you can read my previous article on the different ways of providing injection gateways for containers IOCDI.aspx  .





Figure: - Providing injection gateway
 

Defining the config file


To achieve high customization unity application allows us to specify how the injection will work in the config files ( web.config and app.config ). As this example is a windows command application we will be defining an app.config file.

You can see below a simple template of App.config file from unity perspective. The Configsection is compulsory and keep it as it is. The important section to be noted is the types section which comes under container section. In this we specify which interfaces map to which concrete class. The unity container creates object from this section and inserts in to the customer object through the dependency attribute.
 



Figure: - App.config file
 

The client code


The client code is pretty simple. The first step us we create the unity container object. In the second step we read the unity section. In step 3 we configure the container using the unity section data.

In step 4 we tell the container to create the customer object. This is the most important step of all. In this the container using the config data and the dependency attribute injects either the SQL server database object or oracle database object in to the customer class. This object creation depends on what is defined in the app.config file.

Finally in step 5 we call the save method
 



Figure: - Client code
 

The actual internal working


So what happens internally in the container is that the unity container creates the object of either oracle or SQL server data objects and injects in to the customer class through the dependency defined attribute.
 



Enter the real world of loosely coupling
 

So if you define the ‘clsSqlServer’ class it will create the object of ‘clsSqlServer’ and inject it in to the customer class. If you define the ‘ClsOracle’ class it will inject the ‘clsOracle’ object. You can see in figure ‘The real fun’ how easy it to change implementation by just modifying the config file type sections
 



Figure: - The real fun

Monday, March 25, 2013

C#: Lambda expressions , Action , Func and Predicate

What is a delegate?


A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

Delegates also can invoke methods Asynchronously.

A delegate type maintains three important pices of information :

  1. The name of the method on which it make calls.
  2. Any argument (if any) of this method.
  3. The return value (if any) of this method


Where are Delegates used?

The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place. 

This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.



Defining a Delegate in C#
when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking one integers and returning an double.


Example:
namespace MyPoc
{
   public class Program
    {
       public delegate double CalArea(int r);
        static void Main(string[] args)
        {
            //Create an Instance of CalArea
            //that points to MyClass.CalculateArea().
            CalArea del1 = new CalArea(MyClass.CalculateArea);
            //Invoke CalculateArea() method using the delegate.
            double result = del1(5);
            Console.WriteLine("Result= {0}\n", result);
//Other way of calling deligate
            //CalArea del2=MyClass.CalculateArea;
            // double result1= del2.Invoke(5);
        }     

    }
   
    public class MyClass
    {
      
       public static double CalculateArea(int r)
        {
            return 3.14 * r * r;
        }
    }
}

Anonymous methods

Anonymous methods let you declare a method body without giving it a name. Behind the scenes, they exist as 'normal' methods; however, there is no way to explicitly call them in your code. Anonymous methods can only be created when using delegates and, in fact, they are created using the delegate keyword.

namespace MyPoc
{
   public class Program
    {
       public delegate double CalArea(int r);
        static void Main(string[] args)
        {
            //Create an Instance of CalArea with inline Anonymous Method implementation for CalculateArea
               CalArea del1 = new CalArea(
                delegate(int r)
                {
                    return 3.14 * r * r;
                }

                );
            //Invoke deligate
            double result = del1(5);           
            Console.WriteLine("Result= {0}\n", result);
        }

        //public static double CalculateArea(int r)
        //{
        //    return 3.14 * r * r;
        //}

    }

}

What is Lamda Expression?

Lambda expression is another powerful syntactic sugar making C# functional. In this post, “Lambda expression” simply means “C# Lambda expression”. The native concept of lambda expression will be introduced in the later lambda calculus posts.
According to MSDN:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.
It is just simple functional expression, which looks like number => number > 0. The left side of => is the function parameters, and the right side is the function body.

 public class Program
    {
       public delegate double CalArea(int r);
        static void Main(string[] args)
        {
            //Create an Instance of CalArea with inline Anonymous Method implementation for CalculateArea
            //   CalArea del1 = new CalArea(
            //    delegate(int r)
            //    {
            //        return 3.14 * r * r;
            //    }

            //    );
            ////Invoke deligate using lamda expresssion           
            CalArea del = r => 3.14 * r * r;
            double result = del(5); 
            Console.WriteLine("Result= {0}\n", result);
        }
       }


These are quick definitions of the three classes that are covered in the article:
  • Predicate - delegate that takes parameter(s), runs code using the parameter(s) and always returns a Boolean
  • Func - delegate that takes parameter(s), runs code using the parameter(s) and returns the type that you specify
  • Action - delegate that takes parameter(s), runs code using the parameter(s) and doesn’t return anything


 public class Program
    {
     
        static void Main(string[] args)
        {
            //Lamda expresssion and Func(has input and has output)        
            Func<int,double> del = r => 3.14 * r * r;
            double result = del(5);
            Console.WriteLine("Result= {0}\n", result);

            //Lamda expresssion and Action(has input and has void output/no outout)        
            Action<string> MyAction = r => Console.WriteLine(string.Format("Hello, this is my text :{0}", r));
            MyAction("Vijay");

            //Lamda expresssion and Predicates(has input and return bool) //mostly useed for search and to check if return type is true or false
            Predicate<string> MyPredicate = r => r.Length > 5;
           Console.WriteLine( MyPredicate("VijayMishra"));
          

//use of above in real time
  List<string> myString = new List<string>();
           myString.Add("Vijay");
           myString.Add("VijayMishra");
           string str = myString.Find(MyPredicate);
           Console.WriteLine(str);
        }
       }

C# : Func Type

What is func?
Func<T> is a predefined delegate type for a method that returns some value of the type T

Visit below link for more details:
http://msdn.microsoft.com/en-gb/library/bb549151.aspx

Example

This program uses the lambda expression syntax with Func type instances to store anonymous methods. Each of the Func type instances uses type parameters, and these are specified in the angle brackets < and >.
Lambda
So: The first type parameters are the arguments to the methods, and the final type parameter is the return value.
Generic Class Return
Program that uses Func generic type and lambdas [C#]

using System;

class Program
{
    static void Main()
    {
 //
 // Create a Func instance that has one parameter and one return value.
 // ... Parameter is an integer, result value is a string.
 //
 Func<int, string> func1 = (x) => string.Format("string = {0}", x);
 //
 // Func instance with two parameters and one result.
 // ... Receives bool and int, returns string.
 //
 Func<bool, int, string> func2 = (b, x) =>
     string.Format("string = {0} and {1}", b, x);
 //
 // Func instance that has no parameters and one result value.
 //
 Func<double> func3 = () => Math.PI / 2;

 //
 // Call the Invoke instance method on the anonymous functions.
 //
 Console.WriteLine(func1.Invoke(5));
 Console.WriteLine(func2.Invoke(true, 10));
 Console.WriteLine(func3.Invoke());
    }
}

Output

string = 5
string = True and 10
1.5707963267949


In Main, the program declares and assigns three Func type instances. It uses the full type declaration of the Func types, which includes the parameterized types in the angle brackets.
Note: In the Func types, all of the first parameterized types excluding the last are the argument types.
And: The final parameterized type is the return value. We show two string return values and one double.

The first Func receives an int and returns a string and it is declared as Func<int, string>. The second receives a bool and an int and returns a string. It is declared as Func<bool, int, string>. The third simply returns a value.
Int String Bool
Finally: This program calls the Invoke method on the Func type instances. Each of the Invoke calls uses different parameters.

References:
http://www.dotnetperls.com/func