You don’t need an IoC container or ServiceLocator for everything

Say you have a class that needs to collaborate with another, say a repository:

public class OrderProcessor
{
    public void ProcessPayment(Guid orderId, Payment payment)
    {
        using (var repo = new OrmRepository())
        {
            var order = repo.Find<Order>(orderId);
            order.Pay(payment);

            repo.Save(order);
        }
    }
}

Now that clearly is very hard to test ‘cause it’s directly instantiating the repository. So we know we have to refactor that and pass the repository instead, so that tests can replace the implementation and make assertions about the interaction (if we want to):

public class OrderProcessor
{
    private OrmRepository repository;

    public OrderProcessor(OrmRepository repository)
    {
        this.repository = repository;
    }

    public void ProcessPayment(Guid orderId, Payment payment)
    {
        var order = this.repository.Find<Order>(orderId);

        order.Pay(payment);

        this.repository.Save(order);
    }
}...

Read full article

No Comments