Hi
I'm having trouble figuring out how to resolve objects that depend on objects that are non deterministically created at runtime. What is the best approach?
Imagine something like a word processor. For each document you open, you probably want to create a large number of objects that depend on the document object.
As an example, you want to get a hold of an instance of a DocumentEditor:
public class DocumentEditor {
public DocumentEditor(IDocument document,
ISpellChecker spellChecker,
IWordCounter wordCounter) {
...
}
}
So far, I have considered two approaches but neither seems like a good fit:
Using factories that get injected
The problem with this approach is that you can end up with a factory for each type you need to create. I.e.
public interface ISpellCheckerFactory {
ISpellChecker Create(IDocument document);
}
public interface IWordCounterFactory {
IWordCounter Create(IDocument document);
}
public class DocumentEditorFactory {
public DocumentEditorFactory(ISpellCheckerFactory spellCheckerFactory,
IWordCounterFactory wordCounterFactory) {
...
}
public DocumentEditor Create(IDocument document) {
...
}
}
Add another 50 classes and you see the problem...
Using nested containers
Using nested containers removes the need to create a zillion factories. It is actually pretty compact (example using Unity):
var child = container.CreateChildContainer();
child.RegisterInstance<IDocument>(theDocument);
child.Resolve<DocumentEditor>();
The drawback of this approach is that the container leaks all over the place.
(As a side note, implementing in unity this is a bit tricky. See for instance: http://stackoverflow.com/questions/530405/unity-how-to-register-types-in-the-main-container-but-resolve-in-a-child-conta)
Hybrid approach
It should be possible to combine the two by implementing a DocumentEditorFactory that creates nested containers and uses the child container to resolve dependencies.
Analysis paralysis at its best...