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:
[csharp]
namespace AutofacHelloWorld
{
public interface IExample
{
string PrintHelloWorld();
}
}
[/csharp]
And this is class which implement IExample:
[csharp]
namespace AutofacHelloWorld
{
public class Example : IExample
{
public string PrintHelloWorld()
{
return “Hello world!”;
}
}
}
[/csharp]
And we need some of factory which uses autofac:
[csharp]
using Autofac;
namespace AutofacHelloWorld
{
public class Factory
{
private static IContainer container;
public static T Get
{
if (container == null)
{
var builder = new ContainerBuilder();
builder.RegisterType
container = builder.Build();
}
return container.Resolve
}
}
}
[/csharp]
And this is our main class:
[csharp]
using System;
namespace AutofacHelloWorld
{
class Program
{
static void Main(string[] args)
{
IExample example = Factory.Get
Console.WriteLine(example.PrintHelloWorld());
Console.ReadKey();
}
}
}
[/csharp]
And this is result:
And that’s all Folks 😉