In this article, we will develop a simple example to demonstrate the power of the Autofac
Introduction
Autofac is an Inversion of Control (IOC) container for Microsoft .NET.It was introduced in late 2007.It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. This is achieved by treating regular .NET classes as components. In this article, we will develop a simple example to demonstrate the power of the same.
Straight to experiment
First of all we have to download it from here.I am using version 3.0.2.Let us fire up a console application and add reference to Autofac.dll.
Next write the below code
using System;
using Autofac;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var container = BootStrap.Components())
{
container.Resolve<ISpeak>().Speak();
}
Console.ReadKey();
}
}
public interface ISpeak
{
void Speak();
}
public class Cat : ISpeak
{
public void Speak()
{
Console.WriteLine("Cat says Meow");
}
}
public class Dog : ISpeak
{
public void Speak()
{
Console.WriteLine("Dog barks");
}
}
public class BootStrap
{
public static IContainer Components()
{
var builder = new ContainerBuilder();
builder.RegisterType<Cat>().As<ISpeak>();
return builder.Build();
}
}
}
The class BootStrap uses Autofac to decide which implementation of the interface ISpeak to use.In this case it is "Cat".The RegisterType method registers a component to be created through reflection.The container.Resolve() call requests an instance of ISpeak that's set up and ready to use.
References
Dependency Injection with Autofac
Conclusion
In this article we have seen a simple working example with Autofac.Hope this will be helpful.Thanks for reading.Zipped file is attached.