Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

4 Answers 4

up vote 4 down vote accepted

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.

share|improve this answer
    
Does constructor injection put off new-ing things as long as possible? –  JeffO Feb 22 '13 at 17:52
    
It was ill-put -- I've fixed it to say "as far back in your app as possible". –  Nick Hodges Feb 22 '13 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? –  bot Feb 23 '13 at 18:18

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.

i.e.

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.

share|improve this answer
    
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. –  Peri Feb 22 '13 at 20:18
    
I think you missed the point since the OP did not speak about DI frameworks or DI containers. –  Doc Brown Feb 22 '13 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 –  bot Feb 23 '13 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 :) –  bot Feb 23 '13 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. –  Jimmy Hoffa Feb 23 '13 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.

share|improve this answer
1  
+1, clear and concise. –  Doc Brown Feb 22 '13 at 20:45
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? –  bot Feb 23 '13 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);
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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