Autofac – first steps

I want to write something about autofac. It is one of IoC container for Microsoft .NET. You can find very good documentation about it here. I don’t want to persuade you that it’s the best IoC container for .NET but I want to introduce it only.

I recommend you to read it for the begining. I’ll show you very easy example. So, first of all we have to install nuget package:

So, we want to get implementation of this interface:

namespace AutofacHelloWorld
{
    public interface IExample
    {
        string PrintHelloWorld();
    }
}

And this is class which implement IExample:
namespace AutofacHelloWorld
{
    public class Example : IExample
    {
        public string PrintHelloWorld()
        {
            return "Hello world!";
        }
    }
}

And we need some of factory which uses autofac:
using Autofac;
 
namespace AutofacHelloWorld
{
    public class Factory
    {
        private static IContainer container;
 
        public static T Get<T>()
        {
            if (container == null)
            {
                var builder = new ContainerBuilder();
                builder.RegisterType<Example>().As<IExample>();
                container = builder.Build();
            }
 
            return container.Resolve<T>();
        }
    }
}

And this is our main class:
using System;
 
namespace AutofacHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            IExample example = Factory.Get<IExample>();
            Console.WriteLine(example.PrintHelloWorld());
            Console.ReadKey();
        }
    }
}

And this is result:

And that’s all Folks 😉