Click here to Skip to main content
15,860,943 members
Articles / Programming Languages / C#

Define Your Own IoC Container

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
23 Mar 2012CPOL1 min read 50.6K   20   13
How to define a simple IoC Container

This is a simple IoC Container.

Last year, I was assigned to develop an IoC container for R&D purposes which made me start working with IoC Containers. I share with you here part of it as I think it might help you a lot when you develop your own container.

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about eliminating dependencies from your code. Dependency Injection is well-known as “Inversion of Control” whose principle is – “Don’t call us, we’ll call you”. So we can say that IoC is the principle whereas DI is the way of implementation. There are three popular ways of Inversion of Control, namely:

  1. Constructor Injection
  2. Method Injection
  3. Property Injection

I am not going to discuss about IoC or DI, rather I want to show how to implement your own IoC Container. However, if you want to know the details about IoC and DI, please have a look at this link.

Let's move to our code portion:

C#
public static class IoC
{
    private static readonly IDictionary<Type, 
    Type> types = new Dictionary<Type, Type>();
    private static readonly IDictionary<Type, 
    object> typeInstances = new Dictionary<Type, object>();
    public static void Register<TContract, TImplementation>()
    {
        types[typeof(TContract)] = typeof(TImplementation);
    }
    public static void Register<TContract, TImplementation>(TImplementation instance)
    {
        typeInstances[typeof(TContract)] = instance;
    }
    public static T Resolve<T>()
    {
        return (T)Resolve(typeof(T));
    }
    public static object Resolve(Type contract)
    {
        if (typeInstances.ContainsKey(contract))
        {
            return typeInstances[contract];
        }
        else
        {
            Type implementation = types[contract];
            ConstructorInfo constructor = implementation.GetConstructors()[0];
            ParameterInfo[] constructorParameters = constructor.GetParameters();
            if (constructorParameters.Length == 0)
            {
                return Activator.CreateInstance(implementation);
            }
            List<object> parameters = new List<object>(constructorParameters.Length);
            foreach (ParameterInfo parameterInfo in constructorParameters)
            {
                parameters.Add(Resolve(parameterInfo.ParameterType));
            }
            return constructor.Invoke(parameters.ToArray());
        }
    }
}

Now from your bootstrapper class, you need to register your class like:

C#
Service svc= new Service ();
IoC.Register<IService , Service >(svc);

On subsequent classes, you just need to inject the Interface or class that you register like:

C#
private IService currentSvc = null;
public LoginServices(IService  submittedService)
{
    this.currentSvc =submittedService;
}

Very very simple!!!! We love simple, don’t we?

Updated: 19 March 2012

Example: Say this is my Interface:

C#
public interface ILogger
{
    void Log(string submittedMsg);
}

The Logger class implements this interface.

C#
public class Logger :ILogger
{
    public void Log(string submittedMsg)
    {
        if (!string.IsNullOrEmpty(submittedMsg))
        {
            Console.WriteLine(string.Format("[{0}] {1}\r\n", DateTime.Now, submittedMsg));
            Console.Read();
        }
    }
}

In this ConsoleLogger class, I inject the ILogger to its constructor.

C#
public class ConsoleLogger
{
   private ILogger logger = null;

   public ConsoleLogger(ILogger submittedLogger)
   {
       this.logger = submittedLogger;
       this.DisplayMessage();
   }

   public void DisplayMessage()
   {
       logger.Log("Hi..See it is working!!");
   }
}

Register and Resolve options:

C#
class Program
{
    static void Main(string[] args)
    {
        IoC.Register<ILogger, Logger>();

        IoC.Register<ConsoleLogger, ConsoleLogger>();
        ConsoleLogger objCOnsoleLogger=IoC.Resolve<ConsoleLogger>();       
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer RightKnack Limited
Bangladesh Bangladesh
A big fan of getting down the latest cutting-edge technologies to the ground to innovate exceptionally amazing ideas.

My Blog: http://rashimuddin.wordpress.com/

My Email: rashimiiuc at yahoo dot com

Comments and Discussions

 
Questionhave a Question Pin
Member 1310172318-Apr-17 0:30
Member 1310172318-Apr-17 0:30 
SuggestionAn improvement Pin
dcjpriv26-Mar-12 14:04
professionaldcjpriv26-Mar-12 14:04 
GeneralMy vote of 5 Pin
enamur18-Mar-12 19:59
enamur18-Mar-12 19:59 
GeneralRe: My vote of 5 Pin
Md. Rashim Uddin18-Mar-12 20:10
Md. Rashim Uddin18-Mar-12 20:10 
GeneralRe: My vote of 5 Pin
Md. Rashim Uddin18-Mar-12 20:12
Md. Rashim Uddin18-Mar-12 20:12 
GeneralRe: My vote of 5 Pin
enamur18-Mar-12 21:20
enamur18-Mar-12 21:20 
GeneralRe: My vote of 5 Pin
Md. Rashim Uddin18-Mar-12 21:30
Md. Rashim Uddin18-Mar-12 21:30 
GeneralMy vote of 5 Pin
Saiyed Alam18-Mar-12 9:31
Saiyed Alam18-Mar-12 9:31 
GeneralRe: My vote of 5 Pin
Md. Rashim Uddin18-Mar-12 20:10
Md. Rashim Uddin18-Mar-12 20:10 
QuestionExample Please Pin
Kevin Marois15-Mar-12 6:12
professionalKevin Marois15-Mar-12 6:12 
AnswerRe: Example Please Pin
Md. Rashim Uddin15-Mar-12 8:21
Md. Rashim Uddin15-Mar-12 8:21 
General5 - Re: Example Please Pin
Kevin Marois15-Mar-12 8:28
professionalKevin Marois15-Mar-12 8:28 
GeneralRe: 5 - Re: Example Please Pin
Md. Rashim Uddin15-Mar-12 8:32
Md. Rashim Uddin15-Mar-12 8:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.