Consider a module that is responsible for parsing files of any given type. I am thinking of using the strategy pattern to tackle this problem as I have already explained over here. Please refer to the linked post before proceeding with this question.

Consider class B that needs the contents of the product.xml file. This class will need to instantiate the appropriate concrete implementer of the Parser interface to parse the XML file. I can delegate the instantiation of the appropriate concrete implementer to a Factory such that class B "has-a" Factory. However, class B will then "depend" on a Factory for instantiating the concrete implementer. This means that the constructor or a setter method in class B will need to be passed the Factory.

Therefore, the Factory and class B that needs to parse a file will be tightly coupled with each other. I understand that I may be completely wrong about whatever I have explained so far. I would like to know whether I can use dependency injection in a scenario where the dependency to be injected is a Factory and what would be the right way to implement this so I can take advantage of areas such as mocking the Factory in my unit tests.

4 Answers 4


The right way to do this is to depend on an interface, and then inject an implementation of that interface into Class B.

An interface is just about the thinnest thing that you can depend on -- I liken it to trying to grab a wisp of smoke. Code has to couple to something or else it won't do anything, but coupling to an interface is about as decoupled as you can get, yet interfaces can provide all the functionality that you could want.

So have Class B's constructor take an interface to the class it needs, and have the factory produce that class as an implementer of the interface. Don't depend on the factory, depend on the interface, and have the factory provide an implementation of that factory.

So yes, you will be using dependency injection, but there's nothing wrong with that. Dependency injection -- particularly simple constructor injection -- should be the "normal" way of doing things. Simply put off new-ing things as far back in your app (and as close to the first line of main) as possible, and hide the new call in a class designed specifically for creating things.

Bottom line: Don't be hesitant to inject dependencies. That should be the normal way of doing things.

  • Does constructor injection put off new-ing things as long as possible?
    – JeffO
    Commented Feb 22, 2013 at 17:52
  • It was ill-put -- I've fixed it to say "as far back in your app as possible". Commented Feb 22, 2013 at 19:52
  • Yes. I was thinking of depending on the Parser interface instead of a factory. Now if another class uses class B, it will have to depend on the interface that class B depends on. This will keep continuing all the way up to the top level class. This top level class will have to finally use a factory to instantiate the appropriate concrete instance of the Parser. Should the top level class depend on a factory or should it use the factory directly inside its methods?
    – CKing
    Commented Feb 23, 2013 at 18:18
  • 1
    Well said : Don't be hesitant to inject dependencies Commented Jun 26, 2018 at 16:34

I think your premise is a little confused here, you speak of injecting a factory, but the factory pattern is a creational pattern whose purpose was to do a subset of what a dependency injection framework does, when DI frameworks weren't prevalent this pattern was useful for that reason. However if you have a DI framework, you no longer really need a factory as the DI framework can fulfill the purpose the factory would have fulfilled.

That said, let me explain a bit about dependency injection and how you would generally use it.

There's a variety of ways to do dependency injection, but the most common are constructor injection, property injection, and direct DIContainer. I'll speak regarding constructor injection as property injection is the wrong approach most of the time (the right approach some of the time), and DIContainer access is not preferable except when you absolutely cannot do either of the other approaches.

Constructor injection is where you have the interface for a dependency and a DIContainer (or factory) that knows the concrete implementation for that dependency, and wheresoever you need an object that depends on that interface, at construction time you hand the implementation from the factory to it.


IDbConnectionProvider connProvider = DIContainer.Get<IDbConnectionProvider>();
IUserRepository userRepo = new UserRepository(connProvider);
User currentUser = userRepo.GetCurrentUser();

Many DI frameworks can simplify this significantly to where your DIContainer will inspect the constructor of UserRepository for interfaces it knows concrete implementations for, and will automatically hand those to it for you; this technique is frequently called Inversion of Control, though DI and IoC are both terms which get interchanged a lot and have vague(if any) differences.

Now if you're wondering how the overarching code accesses the DIContainer, well you can either have a static class for accessing it or what is more appropriate is that most DI frameworks allow you to new up a DIContainer, wherein it will actually just behave as a wrapper to an internal singleton dictionary for the types which it knows to be concrete for given interfaces.

That means, you can new up the DIContainer anywhere you want in the code and effectively get the same DIContainer that you had already configured to know your interface-to-concrete relationships. Usual means of hiding the DIContainer from parts of the code which shouldn't interact with it directly is to simply ensure only the necessary project(s) have a reference to the DI framework.

  • 1
    I don't fully agree with first paragraph. There are still scenarios where you depend on a factory (implementing inteface) that is injected by DI container. Commented Feb 22, 2013 at 20:18
  • I think you missed the point since the OP did not speak about DI frameworks or DI containers.
    – Doc Brown
    Commented Feb 22, 2013 at 20:42
  • @Jimmy Hoffa While you made some very interesting points, I am aware of IoC containers such as Spring and the cconcept of Dependency Injection. My concern was regarding a scenario where you don't use an IoC framework in which case, you need to write a class that will instantiate your dependencies for you. If class A depends on interface B and class C uses class A, then class C depends on interface B. Someone needs to give Class C a Class B ce. Should class C then depend on cla
    – CKing
    Commented Feb 23, 2013 at 18:00
  • If class A depends on interface B and class C uses class A, then class C depends on interface B. Someone needs to give Class C an interface B. Should class C then depend on interface B or should it depend on the class that instantiated the dependencies I.e the factory. You seem to have answered this question in your answer but with an information overload :)
    – CKing
    Commented Feb 23, 2013 at 18:10
  • @bot like I said at the preface, in large part you can treat factories as a subset of the functionality of a DI container, it's not true in all scenarios as Doc Brown mentioned, but look at my code sample and replace DIContainer with DbConnectionFactory and the concept still stands that you would retrieve the concrete implementation from your DI/Factory/etc and hand it in to consumers of the type at their construction time. Commented Feb 23, 2013 at 19:43

You can pass a factory via dependency injection just like you pass anything else, don't let the recursiveness of the situation confuse you. I don't know what else to say about implementing it - you already know how to do dependency injection.

I use DI to inject factories pretty regularly.

  • 1
    If a class depends on a Factory, you will need to mock the factory when unit testing that class. How do you go about doing that? Let the class depend on a factory interface?
    – CKing
    Commented Feb 23, 2013 at 18:21

There's nothing wrong in injecting factories. It is standard way if you can't decide during build of 'parent' object what kind of dependency you will need. I think example will explain it best. I will use c# because I don't know java.

class Parent
    private IParserFactory parserFactory;
    public Parent(IParserFactory factory)
        parserFactory = factory

    public ParsedObject ParseFrom(string filename, FileType fileType)
        var parser = parserFactory.CreateFor(fileType);
        return parser.Parse(filename);

Your Answer

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

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