Click here to Skip to main content
15,905,420 members
Please Sign up or sign in to vote.
2.50/5 (4 votes)
See more:
I want to create my own custom IoC container with the explanation for every step.Can anyone please help me out?
Posted

Well, it is pretty simple, as a matter of fact, here is the full source code for the container:

C#
public class DemoContainer
{
    public delegate object Creator(DemoContainer container);

    private readonly Dictionary<string, object> configuration
                   = new Dictionary<string, object>();
    private readonly Dictionary<Type, Creator> typeToCreator
                   = new Dictionary<Type, Creator>();

    public Dictionary<string, object> Configuration
    {
        get { return configuration; }
    }

    public void Register<T>(Creator creator)
    {
        typeToCreator.Add(typeof(T),creator);
    }

    public T Create<T>()
    {
        return (T) typeToCreator[typeof (T)](this);
    }

    public T GetConfiguration<T>(string name)
    {
        return (T) configuration[name];
    }
}

Not really hard to figure out, right? And the client code is as simple:

C#
DemoContainer container = new DemoContainer();
//registering dependecies
container.Register<IRepository>(delegate
{
    return new NHibernateRepository();
});
container.Configuration["email.sender.port"] = 1234;
container.Register<IEmailSender>(delegate
{
    return new SmtpEmailSender(container.GetConfiguration<int>("email.sender.port"));
});
container.Register<LoginController>(delegate
{
    return new LoginController(
        container.Create<IRepository>(),
        container.Create<IEmailSender>());
});

//using the container
Console.WriteLine(
    container.Create<LoginController>().EmailSender.Port
    );
 
Share this answer
 
v2
Read this[^] to get links to several different IOC Containers. You can look them over and pick the one you like best.
 
Share this answer
 
Have a read of this article by Sacha Barber Barbarian IoC[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900