I find it difficult to figure out how to resolve objects that depend on objects that are not deterministic when 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 an instance of DocumentEditor:
public class DocumentEditor {
public DocumentEditor(IDocument document,
ISpellChecker spellChecker,
IWordCounter wordCounter) {
...
}
}
So far I have considered two approaches, but none of them seem good:
Using factories that are being introduced
The problem with this approach is that you can create a factory for each type that 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 50 more classes and you will see the problem ...
Using nested containers
. ( Unity):
var child = container.CreateChildContainer();
child.RegisterInstance<IDocument>(theDocument);
child.Resolve<DocumentEditor>();
, .
( , , . . : , ?)
, DocumentEditorFactory, .
...