Let us learn Autofac

Niladri.Biswas
Posted by in Design Pattern & Practices category on for Beginner level | Points: 250 | Views : 6785 red flag

In this article, we will develop a simple example to demonstrate the power of the Autofac


 Download source code for Let us learn 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.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)