Search code examples
c#language-agnosticloose-couplingservice-locator

Dependency injection or service location?


I'm trying to learn dependency injection, and there are many subtleties to it I'm yet to grasp. One of the books that I've started reading for that purpose is "Foundations of Programming" by Karl Seguin. There's an example about dependency injection:

public class Car
{
    private int _id;

    public void Save()
    {
        if (!IsValid())
        {
            //todo: come up with a better exception
            throw new InvalidOperationException("The car must be in a valid state");
        }

        IDataAccess dataAccess = ObjectFactory.GetInstance<IDataAccess>();
        if (_id == 0)
        {
            _id = dataAccess.Save(this);
        }
        else
        {
            dataAccess.Update(this);
        }
    } 
}

And then he goes ahead and suggest adding another level of indirection, rather than calling ObjectFactory directly in the method:

public static class DataFactory
{
    public static IDataAccess CreateInstance
    {
        get
        {
            return ObjectFactory.GetInstance<IDataAccess>();
        }
    }
}

But isn't this "Service Location" in fact?


Solution

  • It is service locator. There are several of ways to use dependency:

    • aggregation (example case)

    • composition

      • DI in constructor, mandatory (could be injected using SL on upper level)

      • DI in property, optional (could be injected using SL on upper level)

    What to choose depends on many factors, for example whether it is stable or unstable dependency, whether you need to mock it in tests or not etc. There is good book on DI called 'Dependency Injection in .NET' by Mark Seemann.