IoC – Understanding the Need for an IoC Container

cdependency-injectioninversion-of-controlioc-containers

I apologize if this seems like yet another repeat of the question, but every time I find an article regarding the topic, it mostly just talks about what DI is. So, I get DI, but I'm trying to understand the need for an IoC container, which everyone seems to be getting into. Is the point of an IoC container really just to "auto-resolve" the concrete implementation of the dependencies? Maybe my classes tend to not have several dependencies and maybe that's why I don't see the big deal, but I want to make sure that I'm understanding the utility of the container correctly.

I typically break my business logic out into a class that might look something like this:

public class SomeBusinessOperation
{
    private readonly IDataRepository _repository;

    public SomeBusinessOperation(IDataRespository repository = null)
    {
        _repository = repository ?? new ConcreteRepository();
    }

    public SomeType Run(SomeRequestType request)
    {
        // do work...
        var results = _repository.GetThings(request);

        return results;
    }
}

So it only has the one dependency, and in some cases it might have a second or third, but not all that often. So anything that calls this can pass it's own repo or allow it to use the default repo.

As far as my current understanding of an IoC container goes, all the container does is resolve IDataRepository. But if that's all it does, then I'm not seeing a ton of value in it since my operational classes already define a fallback when no dependency passed in. So the only other benefit I can think of is that if I have several operations like this use the same fallback repo, I can change that repo in one place which is the registry/factory/container. And that's great, but is that it?

Best Answer

The IoC container isn't about the case where you have one dependency. It's about the case where you have 3 dependencies and they have several dependencies which have dependencies etc.

It also help you to centralize the resolution of a dependency, and life cycle management of dependencies.

Related Topic