Saturday, September 29, 2012

How to implement a simple IoC Container.

I have decided to take a topic related to software development and dig deeper and write about it on weekends. It will be my weekly learning and knowledge sharing. I have myside projects but its always cool and rewarding to understand how something really works. I do not only want to be a framework user but also a Framework contributor. This can only happen if you deep deeper most of the tools of software and language you use. For this week I want to see how easy is it to implement a simple IoC container that can be used in a project.

 What is an IoC container ?
IoC stands  for Inversion of Control and represents a design pattern used in software development. Wikipedia describes it as " a style of software construction where reusable code controls the execution of problem-specific code. It carries the strong connotation that the reusable code and the problem-specific code are developed independently, which often results in a single integrated application. Inversion of control as a design guideline serves the following purposes:

  • There is a decoupling of the execution of a certain task from implementation.
  • Every module can focus on what it is designed for.
  • Modules make no assumptions about what other systems do but rely on their contracts.
  • Replacing modules has no side effect on other modules. "

 What problem does it try to solve?
 Coupling and dependencies between objects .We let some other objects inject the object when we need it hence we are inverting the control of the process .Passing interfaces into classes and not real objects makes it easy to maintain, add and extend functions of a  feature in an application.

What are the basic prerequisites of building one?
  1. You need a container class.
  2.  In the container class you need a delegate ( A function on the fly!)
  3.  You need a dictionary data structure since you need to look up for keys before sending out objects
  4. Create a function to register the interfaces
  5. Create another function to resolve the interfaces
  6. Use the Container and do something with it.

 Before looking at the code you should understand some concepts like Interfaces, Generics and Delegates in C#. The goal is not build something that I will actually use for production code but just to see and learn the core and basic aspects of an IOC container. Here is the code of the whole project.

   
    /*IOC Container main class */
    public class MyIocContainer
    {
        public delegate object CreateInstance(MyIocContainer container);

        public Dictionary Factory;

        public MyIocContainer()
        {
            this.Factory = new Dictionary();
        }

        public void RegisterInterface(CreateInstance ci)
        {
            if (ci == null)
                throw new ArgumentNullException("ci");

            if (Factory.ContainsKey(typeof(T)))
                throw new ArgumentException("Type already registered");

            Factory.Add(typeof(T), ci);
        }
         
        public T Resolve()
        {
            if (!Factory.ContainsKey(typeof(T)))
                throw new ArgumentException("Type not registered");

            // retrieve the object from the dictionary
            var creator = Factory[typeof(T)];

            // call the delegate returning the object created
            return (T)creator(this);
        }      
    }

   // Create some interfaces to use
    public interface IDownloader
    {
        void GetWebSiteContents(string url);
    }

    public interface IExtractHtmlTags
    {
        void ExtractHtmlTags(string pWebsiteHtmlP);
    }

    // Create some classes to use the interfaces 
    public class WebSiteDownLoader : IDownloader
    {
        public void GetWebSiteContents(string url)
        {   //Some code using the webclient class
            Console.WriteLine("Call using the IoC container to load a website");
        }
    }
   
    public class ExtractHtmlTag : IExtractHtmlTags
    {
        public void ExtractHtmlTags(string websiteDataStream)
        {   
            // Some code here using Regex class<.*?>
            Console.WriteLine("Call using the IoC container to extract html tags");
        }
    }

    // Usage class for the interfaces to perform task.
    public class WebSiteTagRemover
    {
        private readonly IExtractHtmlTags _extractHtml;
        private readonly IDownloader _getWebSite;

     public WebSiteTagRemover(IExtractHtmlTags eTag, IDownloader loader)
        {
           _extractHtml = eTag;
            _getWebSite = loader;
        }

     public void PrintResults()
        {
          _getWebSite.GetWebSiteContents("http://ngalatalla.blogspot.se/");
          _extractHtml.ExtractHtmlTags("website html

");
        }
    }
 
  /*Finally execute and use the container Hooray!! */
internal class Program
    {
        private static void Main(string[] args)
        {   
         //Initiate the container
            var container = new MyIocContainer();

        //Register some interfaces to be used
           container.RegisterInterface(x => new WebSiteDownLoader());
           container.RegisterInterface(x => new ExtractHtmlTag());

      //Resolve the interfaces and get the objects mapped to them
            var getContents = container.Resolve();
            var extract = container.Resolve();

        //Do stuff with the interfaces
        var webTagRemover = new WebSiteTagRemover(extract, getContents);
        webTagRemover.PrintResults();
        }
    }

Results---

If you really want to use an IoC Container in any .Net project, you do not need to implement your own. There are much better options out there. Even if you think of implementing your own, I do not think you can implement any feature or features that they do not already have. They are even more mature and free to use in your projects. Here is a list I composed for some popular ones. I use Ninject in my personal projects because it is mature and easily configured. Choose your own based on your needs.
  Happy programming !

Thursday, April 26, 2012

It is time for Javascript . Are you ready to embrace it?


JavaScript is becoming more and more indispensable for any web developer to know. I have heard lost of bad and good stuff about JavaScript but I ask my self if they are not the programmers who write such bad  JavaScript code  are unpredictable or the differences in the JavaScript engines on various browsers makes us think the language is the problem .I have not  really done much JavaScript development  in my short and exciting career but  I think JavaScript works!! and you can see the power on  every client( mobile phones, tablets etc) connected to the web and needs a good experience. Some known JavaScript APIs are Jquery that  make it very easy to navigate the Dom , NodeJs for server and client development in JavaScript and finally I should not forget to mention Knockout Js which give you a clean way to write clean JavaScript code binned to your model using the MVVM pattern.

I bought my first JavaScript book Eloquent javascript after reading the online version of the book and I think it worth the money. It shows you how to think and code generally and in JavaScript. I am still reading and try to do solve the  assignments in the book before looking at the answers. Its really exciting to play with JavaScript learning about closures and the dynamic and functional nature of the language. I mostly write lots of C# and Jquery code at work but to understand Jquery well , one has to understand JavaScript because that's the source and the beginning.

I have been interested to learn  Html5 and I found it rather amazing how easily you can make an animation process with just a few lines of code. I think Html5 is awesome and is good some browsers now accept it. I hope this stays and combining Html5 , Javascript with SignalR that provides a duplex connection to the server one can do some amazing things in real time. May be i should just write a program to prove this.

I think every web developer can bear with me that there is so much  going on  in the web and is difficult to keep the pace with technologies coming and going. I think the key is know a lot of them but be a master in some of them you love. No matter what is going on the web there is only one language that can do all the magic and that is JavaScript. So maybe its time  for you to learn it to. As a developer, learning new stuff, reading and knowing new technologies should be part of your life style. submit to reddit

Thursday, March 22, 2012

Awesome stuff with C#5 and ASP.NET MVC 4

 I have been having a good  time watching these videos of one of my my favorite writers and developers  Steven Sanderson . These videos are all about the new  Asp.net 4 with Upshot, Knockout, WebApi and how they come together to make building Single page applications (SPA) faster and cleaner. The second video is about C#5  asynchronous operations and how this can be applied to web applications. The code to perform asynchronous calls to the database have been made less chunky and less complicated .Finally one also learns how asynchronous call work underneath and how duplex connection to the server are made and handled by SignalR.  You can read this article  Asynchronous scalable web applications with realtime persistent long running connections with SignalR.
I hope to put the  stuff I leanrt from these videos in my next application, Finally it seems as if there is no running away from JavaScript as a modern software developer who love web applications. Its time to embrace it  and have in your bag of tools. This could be a whole post on its own.
Here are the links to the videos.
submit to reddit

Wednesday, January 11, 2012

Personal development, passion and goals

 I should be proud of my achievements last year  because
  1. I had  my degree in Computer Science,
  2. Got  a good job ,
  3. Had my second child Eric
  4. And bought  a house.
 I had goals for last year and I got more than I could have ever thought of .All this was possible because  of hard work and good planning , being realistic and having a wonderful and supportive wife and  daughter .

Since the beginning of December we have been preparing and packing all our stuff into boxes that we shall take along with us to our new home.Yesterday as I was packing, I came across lots of my notes and code I  wrote when I was studying back in the university. Some of the code was good and I was impressed when  l looked at it and some where really crap and I could not even understand what it does.I ask my self if i really wrote this. I had really had a good laugh at my self. Anyway that was then. I will say I am a better coder now compared to then. I had a lot of passion and still do  but I had to pass my courses so passing my courses was more important than passion and I think its just logical. . I had some nice and though times and really enjoyed some programming courses like Compilier thoery , data structures and algorithims , Computer architecture, C and C++ programming ,web development with .Net and discrete mathematics.

Today I get paid for writing code, and solving complex problems and I consider a pass when my technical boss is happy about it, the customer get his or her problem solved , the code is understandable, clear and concise for the human being to read and understand.

This year I intend to blog more and learn more stuff , deepen my knowledge in some advanced stuff deploy an application to the web or build an app . Learn some real time programming.When will I  do this ? My spare time that I can really own for my self. I love and really enjoy what I do and hope you also do. If you do not, then its time for you to be real to yourself and deepen your knowledge in what you love to do and have passion for. Its never to late to learn and everything is possible.