Note that there are some explanatory texts on larger screens.

plurals
  1. POIoC and dynamic objects
    text
    copied!<p>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?</p> <p>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. </p> <p>As an example, you want to get a hold of an instance of a DocumentEditor:</p> <pre><code>public class DocumentEditor { public DocumentEditor(IDocument document, ISpellChecker spellChecker, IWordCounter wordCounter) { ... } } </code></pre> <p>So far, I have considered two approaches but neither seems like a good fit:</p> <h3>Using factories that get injected</h3> <p>The problem with this approach is that you can end up with a factory for each type you need to create. I.e.</p> <pre><code>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) { ... } } </code></pre> <p>Add another 50 classes and you see the problem...</p> <h3>Using nested containers</h3> <p>Using nested containers removes the need to create a zillion factories. It is actually pretty compact (example using Unity):</p> <pre><code>var child = container.CreateChildContainer(); child.RegisterInstance&lt;IDocument&gt;(theDocument); child.Resolve&lt;DocumentEditor&gt;(); </code></pre> <p>The drawback of this approach is that the container leaks all over the place.</p> <p>(As a side note, implementing in unity this is a bit tricky. See for instance: <a href="https://stackoverflow.com/questions/530405/unity-how-to-register-types-in-the-main-container-but-resolve-in-a-child-conta">How to register types in the main container, but resolve in a child container?</a>)</p> <h3>Hybrid approach</h3> <p>It should be possible to combine the two by implementing a DocumentEditorFactory that creates nested containers and uses the child container to resolve dependencies.</p> <p>Analysis paralysis at its best...</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload