Month List

RecentComments

Comment RSS

Inversion of Control (IoC) and Dependency Injection (DI) and why they are important.

by Ioannis 9. June 2011 19:45

In this blog post, we are going to see how and when  Dependency Injection (DI) and Inversion of Control(IoC) can be applied for writing nice and maintainable code. Note that although there are plenty of tools out there that give you the ability to apply DI out of the box, in this post we are going to implement such a tool on our own gaining valuable insight on the workings of IoC and DI.

 

Suppose that in your code you have two classes (A,B) like the following:

public class A
{
public A(){}
public void Method1(){ }
public void Method2() { }
}

public class B
{
private A _a;
public B()
{
_a = new A();
_a.Method1();
_a.Method2();
}
}

 

That is, we have a class A that has two methods and class B that has a field of type A which is initialized and used in the constructor. Whenever we have such situation we say that “B depends on A” since B needs to create and use A directly. Also, B “has the control” of the creation of A. We will show that dependency graphically with an arrow as follows:

 

image

 

If you implement a new class A1 with the same functionality as A and want to use A1 in B, then you would need to change in B the type of field _a to A1 and its instantiation and recompile the project. If you use A only in one class in your program and your program is a single .exe file (no .dlls) then the merits of IoC cannot be shown and in my opinion you may introduce an unnecessary overhead if you apply it. But let’s see how this changes if the previous condition does not apply.

 

Suppose now that your app is a single .exe file but you have more than one class using A, say B,C,D. Each one of those classes (B,C,D) have a field of type A and use it in their code (B,C,D depend on A).

 

image

 

Switching now from A to A1 requires you to go to “each and every one” of the classes that use A (in a big project this also means that you have to remember which classes are those-in our example B,C,D) and make the appropriate changes. As you must have realized, such process, is error prone and takes time. This problem is created because B,C,D depend on A and B,C,D have the control of creating instances of A.

 

When you use Inversion of Control in the previous situation (changing A to A1) you only need to change a single line of code. So lets see how this works:

 

  1. We create an interface (IA) that has the methods of A. A and A1 should implement this interface.
  2. All classes that use (depend on) A now should use (depend on) IA.
  3. We either need to pass an instance that implement IA in the constructor of those classes or we need to implement a third class Creator that creates objects that implement IA and B,C,D should use this class to get instances that implement IA.

 

If we pass instances that implement IA in the constructors the code looks like the following:

interface IA {
void Method1();
}

public class A:IA {
public A(){}
public void Method1(){ }
}

public class B {
private IA _a;
public B(IA AImplementation) {
_a = AImplementation;
_a.Method1();
}
}

 

In the initial implementation “B had the control of creating A and B depended on A”. In this implementation “the user of B has the control of creating A and B does not depend on A but on IA”. This is Inversion of Control. Now if C,D also follow the same implementation changing from A to A1 does not affect them at all as long as you pass to their constructors and object of type A1 instead of an object of type A. Therefore the previous issue of having to change B,C,D to switch from A to A1 has been solved by using Ioc.

 

Of course, a lot of you would argue that you still have to change the instantiation of A to A1 to each and every one of the classes that create B,C,D to pass the correct parameter in the constructor. For this reason you can use a creator class (a factory) that returns objects that implement IA and use this to create your classes.

 

If we use a creator class and not pass the IA object in the constructor, the code looks like the following:

interface IA {
void Method1();
}

public class A:IA {
public A(){}
public void Method1(){ }
}

public static class Creator {
public A GetIA() {return new A();}
}

public class B {
private IA _a;
public B() {
_a = Creator.GetIA();
_a.Method1();
}
}

See that now _a in B is of type IA and B asks the Creator to get an instance of A. A implements IA. C,D classes would also use IA and the Creator to get an instance that implements A. A1 would need to implement IA also and switching from A to A1 would only require changing the method GetIA in the creator to return a new instance of A1 instead of A. This “Creator” class is usually called a “factory”.

 

Inversion of Control has enabled such a change to be fast, efficient and error free. You can change from A to A1 by changing one line and you can use a new A2 easily by making it implement IA. The drawback is that the amount of code we have written has tripled.

 

Inversion of Control has also another very important benefit in the case where your project uses a .dll. Imagine that you have your ASP.NET MVC project using a class library project which is your business layer. Then, your final deployment consists of the web app and the library dll. If your class A is part of your library and B is part of your web app and you do not use IoC, each time you change from A to A1 you need to recompile the whole project. On the contrary if you use IoC and a factory, the interface IA resides in the library the creator class (factory) resides also in the library and your B class in the web app uses IA. Therefore changing from A to A1 requires you to recompile only the library (.dll) and not all the project facilitating easy and fast deployment in changes.

 

Now wouldn’t  it be nice if we didn’t have to recompile even the library when changing from A to A1? Just have a way to do that by just changing a setting? Can we inject that dependency (A,A1) somehow without having to recompile? This is what we call “Dependency Injection”. How would we implement this without the help of any other libraries?

 

We could keep in a file the class type that needs to be instantiated for the interface and have our “Creator” class (factory) read this file, find out the name of the class that needs to be instantiated and create it by reflection. This would inject the required class in the dependency and thus the term “Dependency Injection”. This means that with dependency injection you do not have to recompile your app when switching from A to A1. The implementation of the creator class for IA should follow the steps below (full code in the project you can download at the end of the post):

 

  1. Open the file with the pairs (interface to implementation).
  2. Find the class name to instantiate
  3. Use reflection to instantiate class from the assembly
  4. Return new object implementing the interface

 

And the file that holds the pair can contain entries as follows:

 

DIandIOCDemo.IA=DIandIOCDemo.A

 

So when should you use Inversion of Control and Dependency Injection?

 

The general rule of thumb is to use it when you have many classes using the methods of a single one and this one may have more than one different “versions”. For example, you are creating your DB Access repositories and you also need to have some fake ones for your tests. Or you have to versions of a class one with lots of debugging info and one without and want to switch between the two at a deployed application.

 

Note that there are fully blown libraries that handle dependency injection such as spring.netthat you should also check out.

 

The project can be downloaded here

Shout it

Tags:

.NET | ASP.NET MVC

Interception and Interceptors in C# (Aspect oriented programming)

by Ioannis 16. January 2011 10:38

In this post, we see how to define specific actions to be executed before or after the execution of every call to a method in our code. This is also known as “intercepting” the execution of a method and is related to AOP (Aspect Oriented Programming). We will explore two different ways of achieving this:

 

  • Using Microsoft’s Unity framework
  • Using the PostSharp library

 

CastleDynamicProxy is another library allowing you to intercept methods and resembles a lot to the Unity framework’s approach so it will not be described here. You can also use .NET framewrok’s Emit namespace or CodeDom to create your intercepting Proxy objects from scratch but this approach is out of the scope of this post.

Aspect Oriented Programming deals with horizontal concerns in the specifications of your programs. Horizontal concerns are requirements that span through every business logic or specific behavior of your system. Take for example the following figure displaying some typical modules of an e-shop application.

Horizontal and Vertical Concerns

The classes of the system that deal with the system’s business logic (charging, product browsing etc), in a good design, do not replicate logic within each other. Those are “Vertical concerns” since they can be considered unrelated. On the contrary, if we want to provide logging for every method in our classes or want to apply security checks we deal with “Horizontal concerns” since they span throughout all the modules of the system.

 

Now, if you imagine implementing the “typical” way those concerns (eg the logging mechanism), you will end up decorating a lot of your “Vertical concern classes” with code like the following:

image

Not very pretty especially if you image replicating this in every class of every “Vertical concern”. This is where Aspect Oriented Programming comes in handy by providing a way of turning those horizontal concerns into “Aspects” which practically means that you find a way of intercepting the execution of those methods adding the extra logic in a single place and thus perform your required actions with as few changes as possible to the initial code.

 

Microsoft’s Unity Framework (link)

Microsoft’s Unity 2.0 comes within Enterprise Library. It is easy to use with the limitation that you need to have all your objects to intercept created through a factory within your code and also the interceptable classes need to implement an Interface or derive from the MarshalByRefObject class.

So lets suppose you have the following class:

public class ClassToIntercept
{
public int ID { get; set; }

public int GetRandomNumber(int min, int max) {
return new Random().Next(min,max);
}
}

 

In your code all objects of this class are instantiated with “new ClassToIntercept()”. You have no way to intercept this with the Unity Framework without changing anything in the class or the object creation places. On the contrary if you have built factories for your classes (that is you never create objects with the new keyword but rather ask a method to create them for you – not a bad programming practice for many reasons) such as:

public static class ClassToInterceptFactory
{
public static ClassToIntercept GetClassToIntercept()
{
ClassToIntercept ReturnClass = new ClassToIntercept();
return ReturnClass;
}
}

 

Now whenever you need a ClassToIntercept object in your code you call the GetClassToIntercept method. Unfortunately, you still cannot intercept the class methods. Your class also needs to derive from MarshalByRef object:

public class ClassToIntercept:MarshalByRefObject
{
public int ID { get; set; }

public int GetRandomNumber(int min, int max) {
return new Random().Next(min,max);
}
}

 

And now you can change your factory as follows:

public static ClassToIntercept GetClassToIntercept()
{
//ClassToIntercept ReturnClass = new ClassToIntercept();
ClassToIntercept ReturnClass = Intercept.ThroughProxy(new ClassToIntercept(),
new TransparentProxyInterceptor(), new[] { new InterceptionClass() });
return ReturnClass;
}

 

Interception will work and what will happen will be determined from the InterceptionClass that will be explained in a minute.

If you wanted to avoid deriving from MarshalByRef you could have implemented an interface for your initial class such as:

public interface IClassToIntercept
{
int GetRandomNumber(int min, int max);
}

 

Have your class implement this interface and your factory return the Interface instead of the class. This would mean that you program your whole software to the Interface and not to the actual class (which is not a bad programming practice either although it cannot be applied easily to any scenario). Nevertheless, if this is the case, then your factory would now be like the following:

public static IClassToIntercept GetClassToInterceptInterface()
{
//IClassToIntercept ReturnClass = new ClassToIntercept();
IClassToIntercept ReturnClass = Intercept.ThroughProxy<IClassToIntercept>(new ClassToIntercept(), new InterfaceInterceptor(),
new[] { new InterceptionClass() });
return ReturnClass;
}

 

For all those to work you need to have the Enterprise Library installed and  add as References Microsoft.Practices.Unity and Microsoft.Practices.Unity.Interceptions. The Interception class is as follows (the Invoke method is the one doing the job!):

public class InterceptionClass:IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces() {
return Type.EmptyTypes;
}

public IMethodReturn Invoke(IMethodInvocation input,GetNextInterceptionBehaviorDelegate getNext){
Console.WriteLine("Before the method");
var methodReturn = getNext().Invoke(input, getNext);
if (methodReturn.Exception == null)
Console.WriteLine("After the method");
else
Console.WriteLine("Ater the method with exception");
return methodReturn;
}

public bool WillExecute {
get { return true; }
}

}

 

 

References

Aspect-Oriented Programming, Interception and Unity 2.0 (Dino Esposito)

Interceptors in Unity (Dino Esposito)

 

Using PostSharp(link)

PostSharp is a great tool and can achieve the most clean interception possible (meaning no changes in your classes and object generation at all even if you do not your factories for object creation and/or interfaces) but it is not a free library. Rather than creating proxies at runtime, it injects code at compile time and therefore changes your initial program in a seamless way to add method interception.

To achieve the same result you include PostsSharp.dll in your project and then create an attribute such as:

[Serializable]
public sealed class TraceAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("Before the method");
}

public override void OnExit(MethodExecutionArgs args)
{
Console.WriteLine("After the method");
}
}

 

Now you can add the following attribute making all methods of ClassToIntercept Intereptable (you can also apply the Trace attribute to classes/methods if you can change the original code):

[assembly: Trace(AttributeTargetTypes = "Interceptions.ClassToIntercept")]

 

The cool thing in this is that you do not change anything else in your code, so your object can be still generated using the new keyword.

 

In this post, I have demonstrated two very easy approached in providing method interceptors n your programs. The complete demo project can be downloaded here

 

Shout it

Domain Specific Languages with M - Part 1/3 Defining the syntax

by Ioannis 10. April 2010 09:07

Say you are implementing software for a company that rents items. And you are presented with some bizarre and complex logic on the way renting fees are calculated. To be more specific requirements come to you in the following form:

“I want a renting fee scenario where an item for the first month is charged 10$ per day. Then, the same item costs 5$ per week for the next two months. Finally, after this period of three months the fee will be 20$ per month. But this is just one scenario…”

Clearly your inclination will be to go talk to the guy, help him write all his scenarios and then come up with a clever algorithm that calculates the fees and (hopefully) a UI where the guy can add more scenarios and persist them in the database.

Or you can implement a DSL. A DSL that allows somebody to express such complex renting-fee scenarios in an easy to use language. Hopefully this language will offer you more expressiveness and flexibility than a nicely constructed UI. From the moment you realize that renting fees will need requirement analysis, you come up with the following DSL:

 

Scenario (“Monthly”)
    For 1 month charge 10$ per day.
    For 2 months charge 5$ per week.
    Eventually charge 20$ per month.
End

 

Clearly this is something that can be given to the guy and ask him to express his renting fee scenarios using this language. At the time he writes his specs, you have work to do:

 

  • Create a database that stores those scenarios in some form.
  • Implement the algorithm that calculates the fees for any arbitrary scenario you may receive.

 

It all boils down to finding a way to parse the language and express meaningful information from it. How does “M” facilitate this process? As you will see you get a lot of out of the box goodies by implementing this DSL in “M”.

 

 Defining the syntax in M

Open Intellipad and select “DSL Grammar Mode”:

 

 

Create a text file that contains a demo scenario like the one we have written above.  Now go ahead and select “Open File as Input and Show Output”:

 

 

This will split your window in three. On the left you have your demo program in your new DSL. In the middle you write your DSL’ s syntax. On the right you get what “M” understands from your syntax and the demo program. Go ahead and write in the middle (where the syntax goes) the following:

 

module RentingApp
{
    language RentLanguage
    {
        syntax Main=any*;
    }
}

 

That is, you define a module named “RentingApp” which contains the syntax of the language “RentLanguage”. The syntax consists of a single rule that matches everything. The rule says that “Main” contains zero of more occurrences of any character. The moment you write these lines, the framework understands the input language and displays it on the right (Note that the result is a set of single characters):

 

 

 Of course this is of little help. Let’s go and make the syntax more specific by providing the following rules:

 

 

module RentingApp
{
    language RentLang
    {
        interleave whitespace = (" " | "\r" | "\n" | "\t")+;
       
        syntax Main=RentCharge*;
        syntax RentCharge="Scenario" "(" ChargeScenarioName ")" ChargeRules "End";
        syntax ChargeRules=(ChargeRule ".")*;
        token ChargeRule= "For" !('.')+ | "Eventually" !('.')+;
       
        syntax ChargeScenarioName=QuotedIdentifier;
        token QuotedIdentifier = '"' !('\r' | '\n' | '"')+ '"';
    }
}

 

The first thing to note is the directive “interleave…” which tells that our language does not take into consideration any spaces or returns or tabs.

The <Main> part consists of one or more <RentCharge> parts. Each <RentCharge> part begins with the word “Scenario“ and an opening “(“, has a <ChargeScenarioName> part followed by a closing “)”, then has a <ChangeRules> part and finally ends with the word “End”.

The <ChargeScenarioName> part is a <QuotedIdentifier> which matches one or more characters within quotes apart from “\r” and \n”.

The <ChargeRules> part consists of zero or more <ChargeRule> parts which end with “.”.

The <ChargeRule> parts start with the word “For” and then matches everything except the “.” or start with “Eventutally” and then anything except “.”.

This is practically how we construct the syntax of the DSL. The full syntax supporting the language we are building for the renting scenarios is as follows:

 

module Renting
{
    language RentLanguage
    {
        interleave whitespace = (" " | "\r" | "\n")+ | Comment;
       
        syntax Main= Charges+;
        syntax Charges=ChargeStartToken "(" ChargeName ")" ChargeBody ChargeEndToken;
        syntax ChargeBody=ChargeRule+;
        syntax ChargeRule=ForToken PeriodAmount Period ChargeToken CurrencyAmount CurrencyToken "per" Period "."
                         |EventuallyToken ChargeToken CurrencyAmount CurrencyToken PerToken Period ".";
        token PeriodAmount=('0'..'9')+;
       
        token Period="week"|"weeks"|"month"|"months"|"days"|"day"|"year"|"years";
        token CurrencyAmount=('0'..'9')+ DecimalSeparator ('0'..'9')* | ('0'..'9')+;
        token ChargeName=QuotedIdentifier;
        token DecimalSeparator=",";
        token ChargeStartToken="Scenario";
        token ChargeEndToken="End";
        token ForToken="For";
        token EventuallyToken="Eventually";
        token CurrencyToken="$";
        token ChargeToken="charge";
        token PerToken="per";
        token Comment = "//" !("\r" | "\n")+;
        token QuotedIdentifier = '"' !('\r' | '\n' | '"')+ '"';
    }
}

 

As you can see we do not hard code any of the literals of the language (such as “Scenario” etc) within the syntax rules. We do that to be able to easily change the spoken language of our DSL (for example from English to Greek). The syntax you see above recognizes all the possible sentences that will be written for the renting scenario and as you may have noticed from the first rule, it accepts more than one renting scenarios at once.

You can download the aforementiond grammar for the English language here and a little different version for the Greek langauge here.

In the next post we will decorate our DSL with attributes and create productions to alter the output of the DSL parser.

 

 

Shout it

kick it on DotNetKicks.com

Tags:

.NET

Powered by BlogEngine.NET 2.0.0.36

ITPRO DevConnections 2011

Creative Commons License

Programming Blogs - BlogCatalog Blog Directory Add to Technorati Favorites

MVP Award


Ioannis Panagopoulos





This blog is using BlogEngine.Net and is hosted in the hoster below. I have not experienced any problems installing BlogEngine.Net in the host and I am satisfied with the host's response times. Therefore I recommend it.


DiscountASP Add