47

Just assume I have some class Foo, that has two dependencies: an ISerializer<T> and an IFileAccessHandler.

Now this class also has other dependencies, functional dependencies. I don't want anyone instantiating this class in an invalid state, so I'd also need to pass a domain object in the constructor.

But how can I have that handled by IoC when I also know what domain object to pass in the moment I'm actually creating class Foo?

I made the domain object a property that I have set by a Factory. So the Factory makes a Service Locator call to get a properly instantiated "Foo" class with it's dependencies, and further fills it up with the correct domain object and returns it.

But is this the best way to go? I would have preferred having the domain object part of my constructor to make it apparant you actually need to work with "Foo".

Any ideas? Am I missing something here?

2 Answers 2

74

The default solution to DI when you can't wire up a concrete type at registration time is to use an Abstract Factory

In your case, I would define an IFooFactory interface:

public interface IFooFactory
{
    Foo Create(DomainClass dc);
}

This will allow you to define a concrete implementation that knows about your infrastructure services.

public class FooFactory : IFooFactory
{
    private readonly ISerializer serializer;
    private readonly IFileAccessHandler fileHandler;

    public FooFactory(ISerializer serializer, IFileAccessHandler fileHandler)
    {
        if(serializer == null)
        {
            throw new ArgumentNullException("serializer");
        }
        if(fileHandler == null)
        {
            throw new ArgumentNullException("fileHandler");
        }

        this.serializer = serializer;
        this.fileHandler = fileHandler;
    }

    public Foo Create(DomainClass dc)
    {
        return new Foo(this.serializer, this.fileHandler, dc);
    }
}

In this way you can protect the invariants of your Foo class, enabling you to stay with Constructor Injection.

In the DI container, you can register the IFooFactory and corresponding implementation. Everywhere you have a DomainClass instance and need a Foo instance, you would then take a dependency on IFooFactory and use that.

33
  • 13
    Because that would be the Service Locator anti-pattern (blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx). The DI Container must not invade the rest of the application. However, some containers (e.g. Windsor) can automatically implement and emit implementations of Abstract Factories, in which case FooFactory would be completely redundant. If you want to use the DI Container, go all the way :) Jul 15, 2010 at 12:28
  • 1
    I agree that Service Locator is anti-pattern, but every rule has exceptions. You should not follow this rule blindly! You wire your objects manually, your abstract factory has incorrect dependencies. This a smell of bad design, is not it? DI container is intended to get rid of this smells, is not it? So use DI container to create Foo! You right :) If you want to use the DI Container, go all the way :) Jul 15, 2010 at 12:51
  • 7
    Dynamic factories á la Windsor aside, why would FooFactory have incorrect dependencies? It still uses Constructor Injection, so you still need the DI Container to wire it up for you. The point is that you can't create Foo without DomainClass, which is only available at run-time. Using the DI Container as a Service Locator is not going to change that, but would add a tight coupling to the DI Container, as well as a logical coupling to Foo. This would only leave you worse off than the above implementation. Jul 15, 2010 at 13:01
  • 2
    Can an abstract factory return a concrete type ? Foo here is a concrete type as you can new it. I thought abstract factory were meant to return only abstractions ? Or am I wrong ?
    – darkey
    Apr 28, 2013 at 1:35
  • 1
    @GetFuzzy An Abstract Factory is also a 'newable', but perhaps this helps: blog.ploeh.dk/2011/03/03/InjectionConstructorsshouldbesimple See also chapter 6 of my book. And here's another take on selecting dependencies based on run-time values: stackoverflow.com/a/22705794/126014 Jul 18, 2014 at 6:11
1

I am also struggling with this issue. Mark's example is constrained in that the FooFactory is creating a concrete class Foo. What if it was to create an IFoo where the implementation is determined during startup configuration? This would imply for every alternative implementation of IFoo (FooA, FooB, etc) you would need a concrete implementation of the corresponding factory (FooAFactory, FooBFactory, etc). This strikes me as redundant.

If the factory is defined at the same level as the implementation and initialization of the Container, I do not see the weakness of referencing the container by the factory. It still keeps references of the container from leaking into the rest of your application.

Best regards,

Metro.

2
  • there is a post that agrees with this point of view (mark^ wrote it) but then every consumer would need to implement their own factory implementation. (just an add on not a good or bad to your post) [blog.ploeh.dk/2012/03/15/ImplementinganAbstractFactory/]
    – workabyte
    Nov 21, 2014 at 22:21
  • @Metro Correct me if I'm not reading your proposal correctly. So your proposal is to have the factory resolve the abstract type using the container? So essentially Service Locator? But a Service Locator call that doesn't hurt your soul as much since implementation of the factory is at the same level as the IoC container?
    – Ash
    Mar 9, 2018 at 3:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.