Inversion Of Control Containers And Factories Aren’t Mutually Exclusive
Posted by Davy Brion on January 23rd, 2010
Julian Birch recently posted a reaction to my reaction to Uncle Bob’s IOC lunacy post. Julian mistakenly thinks that i have a problem with using factories. I definitely don’t have a problem with using factories. I just have a problem with using them in the manner that Uncle Bob suggested in his post. Jeffrey Palermo also recently posted an example of where he thinks using a factory is better than injecting dependencies. I wanted to react to both those posts with a real-world example of where i prefer to use a factory and how i use an IOC container to do so.
As you probably know by now, i’m a big proponent of using IOC containers. I’ve never stated that they should be used in every single application, but using one certainly pays off in most applications, especially as complexity increases gradually. When you use an IOC container, you’ll have much less need for factories. There are however two situations where i certainly prefer to use a factory. And that is when:
- a certain dependency might not always be used by a class and that dependency is expensive to create
- i might need multiple instances of a dependency during the lifetime of a class
A good example of both those situations is when using Agatha’s AsyncRequestDispatcher class from a Silverlight user control. Creating an AsyncRequestDispatcher is expensive because it in turn requires an instance of the AsyncRequestProcessorProxy class. The AsyncRequestProcessorProxy class inherits from WCF’s ClientBase class, and those types are relatively expensive to create. And due to the asynchronous nature of those service calls, you can never deterministically dispose of a AsyncRequestDispatcher instance with absolute certainty that it won’t be disposed before the response of the service call is returned from the service. Because of that, the AsyncRequestDispatcher class was designed to dispose of itself automatically once the response is returned. This effectively means that you’ll need a new instance of AsyncRequestDispatcher whenever you need to make an asynchronous call to an Agatha service.
For most user controls, it obviously doesn’t make sense to inject one instance of the AsyncRequestDispatcher into the user control because you often need to make multiple service calls depending on user interactions or other events. A good way to deal with this is obviously to ask a factory to create the AsyncRequestDispatcher whenever you need one. Which is why Agatha offers the AsyncRequestDispatcherFactory class, which looks like this:
public interface IAsyncRequestDispatcherFactory
{
IAsyncRequestDispatcher CreateAsyncRequestDispatcher();
}
public class AsyncRequestDispatcherFactory : IAsyncRequestDispatcherFactory
{
public IAsyncRequestDispatcher CreateAsyncRequestDispatcher()
{
return IoC.Container.Resolve<IAsyncRequestDispatcher>();
}
}
Now, some of you are probably thinking: what is the difference between this and Uncle Bob’s example? Well, unlike Uncle Bob’s example this factory is not responsible for registering the required components to create an AsyncRequestDispatcher with the container. It merely resolves an instance and returns it. And yes, it uses the container to do so. I could actually just new up an AsyncRequestDispatcher myself but then the factory would also have to know about its dependencies and make sure it’d be able to create them. If those dependencies have dependencies of their own, i’m back to dealing with dependencies manually which is exactly what i’m trying to avoid throughout my codebase.
I can’t come up with a single reason why this would be wrong, but some of you probably will so feel free to point out those reasons
The benefit of this factory is that it enables me to delay the instantiation of an expensive dependency, and it also enables me to get more than one instance if i need to during the lifetime of a single object. At the same time, it doesn’t have any of the downsides of Uncle Bob’s approach. Also, this approach is something that you won’t need to resort to throughout your codebase, it’s more for edge-cases.
Now, how do we use this factory? Instead of new’ing the factory manually like Jeffrey does in his example, the factory is registered with the IOC container and i simply inject the factory into the class that needs to use it. This still enables me to change implementations of both the factory as well as the instances the factory needs to create. And it also makes it easy to stub or mock the factory during tests. I get all of the benefits from using Dependency Injection and an IOC container, and i have yet to notice any downsides to this approach. But again, i only use this approach in the 2 situations i mentioned in the beginning of this post. In most cases, you really don’t need factories anymore. And when you do, just leverage your IOC container to make the factory as simple and dumb as possible.

January 23rd, 2010 at 5:33 pm
To me it sounds like you agree quite a bit with uncle bob. It certainly seems like we agree too since factories often don’t need to be represented as interfaces.
January 23rd, 2010 at 6:08 pm
Gah, in my comment above, the angle brackets was taken for tags, here’s a repost. If you can delete the previous one, please do so.
I’ve solved a similar problem with my own IoC container. Every service you register will have a sibling service being registered that will resolve to IServiceFactory{ServiceInterfaceType}. So, if you register a service like IEmployeeRepository, another service for IServiceFactory{IEmployeeRepository} will be registered for you, automatically. If you resolve for the service, the container will go about its business as usual, but if you resolve the factory service, you can then later on resolve the actual service from that factory service. If the service isn’t singleton, or container-scoped, you can also resolve it multiple times, for multiple instances.
Since this is handled by my container automatically, I can use the factory service in constructor calls to my other services, and have the factory automatically injected for me. This way I can easily flag in the code that my service depends on another service, but it either has lazy-resolution scenarios, or multiple-resolution scenarios, without having to just inject the whole container.
January 23rd, 2010 at 7:20 pm
The current IoC hornets nest has provided plenty of reading.
I have recently used the same approach as you in a project I am working on. Simply passing in the a dependency (a list of launch application buttons to show) did not fit as this would require either the container or the calling function (main) to assume responsibility for the contents. A factory made sense as this provided a single configuration point. The factory implementation simply called the container to resolve the specific button types and their dependencies.
It was my tests that drove me to that decision, either too much setup, too much direct access to the container.
The factory + container allows me to defer creation until I need it while simplifying my tests and the injected dependencies. I agree I can’t see a downside.
While calling the container directly is something that should be limited, it feels like a reasonable thing to do inside a factory class. Which after all that is its traditional role. Further more it has pushed the access to the container further to the edges of the design.
January 23rd, 2010 at 8:54 pm
Having seen your (very clear) example, I think we agree more than we disagree here. I think probably our biggest disagreement is over how we interpreted Uncle Bob’s original post, rather than what best practice is. Your example is pretty much exactly the scenario/solution I was trying to describe.
The only change I’d make is to take the container as a constructor dependency rather that make it a global variable. Jeffrey did something similar in his example, where he introduced a (to my mind) unnecessary global variable to abstract out the container. I know it’s rare to want a second container in the same process, but making it an instance isn’t usually that hard.
Thank you,
Julian.
January 23rd, 2010 at 8:58 pm
Davy,
Good point you have there. However, if you’re using the factory just as a facade for the container, than why bother hand coding it?
In Windsor all you need is the interface IAsyncRequestDispatcherFactory and you can have the container do the implementation for you.
January 24th, 2010 at 3:54 am
Or similarly with Autofac, just use Func<IAsyncRequestDispatcher> and the container will automatically provide an implementation for you. Zero-friction
January 24th, 2010 at 10:59 am
@Jeffrey
i don’t know how carefully you read this post but i really don’t agree with Uncle Bob about the IOC thing _at all_. He advocates using manual DI and when things get a bit more complex, to switch to factories. Those factories that he suggests not only know about the dependencies of the classes they need to create, they’re also responsible for the registration of them. That’s pretty much the exact opposite of the kind of factory i showed in this post. And about not needing to represent factories as interfaces, i think we disagree on that as well. My post clearly shows that the factory does implement an interface and that i have it injected in the class that needs instances created by the factory. I even mention that this enables me to switch the implementation of both the factory, as well as the instances that are created. I can’t really think of any reason why i’d want to new up a factory instance… i’d have to have some kind of static hook into the factory to replace the type of the instance being created by the factory during tests. Which is another thing that i’m actively trying to avoid with DI.
If you still think that i agree with Uncle Bob or with you about this whole thing, i’d really like to see a more detailed explanation as to where you see the similarities in thoughts. Because i really don’t see them, quite the opposite in fact
January 24th, 2010 at 11:03 am
@Krzysztof and @Nicholas
i already know about those features, and think they’re great
but i can’t use anything container-specific in Agatha since it needs to work with multiple containers…
January 25th, 2010 at 9:41 am
[...] Inversion Of Control Containers And Factories Aren’t Mutually Exclusive – Davy Brion picks up on some feedback about the use of Factories as a part of the DI debate, ans shows how he goes about using factories with Inversion of Control. [...]
January 25th, 2010 at 1:50 pm
@Davy interestingly, if we invert the relationship between Agatha and the container
then using an automatically-implemented interface or Func would aid portability.
The big hurdle is getting an inverted “Common Service Locator” happening. Just wrote about this (in perhaps too much detail) here: http://nblumhardt.com/2010/01/the-relationship-zoo/ – hope this makes some sense in your scenario, as frameworks like Agatha would be a primary consumer.