Investigating Autofac

Time to try some different IoC frameworks. Let’s take a look at the basics of Autofac. Using the simple IService implementation and a client with a constructor that requires the IService injected into we get the following code.

public interface IService
{
   void Run();
}

public class LocalService : IService
{
   public void Run()
   {
      Console.WriteLine("LocalService");
   }
}

public interface IClient
{
   IService Service { get; }

   void Run();
}

public class Client : IClient
{
   public Client(IService service)
   {
      Service = service;
   }

   public IService[] Service { get; private set; }

   public void Run()
   {
      Service.Run();
   }
}

We can set up bindings in code using the following

var builder = new ContainerBuilder();
builder.RegisterType().As();
builder.RegisterType().As();

var container = builder.Build();

var client = container.Resolve();
client.Run();

If we have multiple IService implementations then changing the Client to

public interface IClient
{
   IService[] Service { get; }

   void Run();
}

public class Client : IClient
{
   public Client(IService[] service)
   {
      Service = service;
   }

   public IService[] Service { get; private set; }

   public void Run()
   {
      foreach(IService service in Service)
         service.Run();
   }
}

var builder = new ContainerBuilder();
builder.RegisterType().As();
builder.RegisterType().As();
builder.RegisterType().As();

var container = builder.Build();

var client = container.Resolve();
client.Run();

Now let’s remove the constructor and use property injection. The client changes to

public class Client : IClient
{
   public IService[] Service { get; set; }

   // the run method as before
}

There’s no attributes or the likes to suggest that a property should be injected into. The change is in the binding code, just changing the Client registration code to

builder.RegisterType<Client>().As<IClient>().PropertiesAutowired();