Sunday, March 7, 2010

MSBuild with dependency injection

I am about to start refactoring a MSBuild file with around 1000 lines of xml, and I find that the targets are heavily dependent on each other.

Maybe dependency injection can help here?!

In MSBuild this could look something like this:

UserInterface.xml:
<Import Project="ApplicationService.xml" />
<Import Project="Repository.xml" />
(or <Import Project="FakeRepository.xml" />)
<Target Name="UserInterface-Action">
  <CallTarget Targets="ApplicationService-Action" />
</Target>


ApplicationService.xml:
<Target Name="ApplicationService-Action">
  <CallTarget Targets="IRepository-Action" />
</Target>


Repository.xml:
<Target Name="IRepository-Action">
  <Message Text="Repository action" />
</Target>


FakeRepository.xml:
<Target Name="IRepository-Action">
  <Message Text="Fake repository action" />
</Target>


For comparison, here is the corresponding structure in C#:
public class UserInterface
{
  private readonly IRepository repository;

  public UserInterface(IRepository repository)
  {
    this.repository = repository;
  }

  public void Action()
  {
    var service = new ApplicationService(this.repository);
    service.Action();
  }
}

public class ApplicationService
{
  private readonly IRepository repository;

  public ApplicationService(IRepository repository)
  {
    this.repository = repository;
  }
  
  public void Action()
  {
    this.repository.Action();
  }
}

public interface IRepository
{
  void Action();
}

public class Repository : IRepository
{
  public void Action()
  {
    System.Console.WriteLine("Repository action");
  }
}

public class FakeRepository : IRepository
{
  public void Action()
  {
    System.Console.WriteLine("Fake repository action");
  }
}

No comments: