Search This Blog

Friday, October 30, 2015

Dependency Injection in C# with Autofac - real world example

C# > Patterns > Dependency Injection  > Autofac

Autofac is an addictive Inversion of Control container for .NET 4.5, Silverlight 5, Windows Store apps, and Windows Phone 8 apps

Source: http://autofac.org/

Dependency Injection in C# with Autofac - real world example

using Autofac;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public class Programmer
    {
        public string Name { get; set; }
        public IList<string> Skills { get; set; }
    }




    public class Project
    {
        public string Name { get; set; }
        readonly IList<Programmer> _programmers;
        readonly IDispatcher _dispatcher;

        public Project(IList<Programmer> programmers, IDispatcher dispatcher)
        {
            _programmers = programmers;
            _dispatcher = dispatcher;
        }

        public void FindProgrammers()
        {
            var programmers = _programmers.Where(e => e.Skills.Contains("VB"));

            foreach (var p in programmers)
                _dispatcher.Notify(p);
        }
    }

    public interface IDispatcher
    {
        void Notify(Programmer programmer);
    }

    public class Email : IDispatcher
    {
        private readonly string _message;

        public Email(string message)
        {
            _message = message;
        }

        public void Notify(Programmer programmer)
        {
            Console.WriteLine("Sent message {0} to {1}", _message,  programmer.Name);
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Programmer> lst = new List<Programmer>();
            Programmer p = new Programmer();
            p.Name = "Dan";
            p.Skills = new List<string>();
            p.Skills.Add("VB");
            lst.Add(p);

            Email email = new Email("Notification email message");

            ContainerBuilder autofac = new ContainerBuilder();
            autofac.Register(o => new Project(o.Resolve<IList<Programmer>>(), o.Resolve<IDispatcher>()));

            autofac.RegisterType<Email>().As<IDispatcher>();
            autofac.RegisterInstance(lst).As<IList<Programmer>>();
            autofac.RegisterInstance(email).As<IDispatcher>();
           
            using (var container = autofac.Build())
            {
                container.Resolve<Project>().FindProgrammers();
            }

        }
    }
}