Note that there are some explanatory texts on larger screens.

plurals
  1. PODI-Container: Howto pass configuration to objects
    primarykey
    data
    text
    <p>Sometimes I have classes which need to get some information for construction. I am not talking about references to other objects (which will be injected) but about (for instance) strings which are holding unique information:</p> <pre><code>// Scoped as singleton! class Repository { public Repository( InjectedObject injectedObject, string path ) { ... } } </code></pre> <p>How do you get this string injected? One possiblity is to write an <code>Init()</code> method and to avoid injection for the string:</p> <pre><code>class Repository { public Repository( InjectedObject injectedObject ) { ... } public void Init( string path ) { ... } } </code></pre> <p>Another possibility is to wrap the information into an object, which can be injected:</p> <pre><code>class InjectedRepositoryPath { public InjectedRepositoryPath( string path ) { ... } public string Path { get; private set; } } class Repository { public Repository( InjectedObject injectedObject, InjectedRepositoryPath path ) { ... } } </code></pre> <p>This way I'd have to create an instance of <code>InjectedRepositoryPath</code> during the initialisation of my DI-Container and register this instance. But I need such an unique configuration object for every similar class.</p> <p>Of course I can resolve a <code>RepositryFactory</code> instead of the <code>Repository</code> object, so the factory would ask me for the path:</p> <pre><code>class RepositoryFactory { Repository Create( string path ) { ... } } </code></pre> <p>But again, this is one factory just for a singleton object ...<br> Or, finally, since the path will be extracted from a configuration file, I could skip passing around the string and read the config in my constructor (which is probably not as optimal, but possible):</p> <pre><code>class Repository { public Repository( InjectedObject injectedObject ) { // Read the path from app's config } } </code></pre> <p>What's your favorite method? For non-singleton classes you have to use imho the <code>Init()</code> or factory solution, but what about singleton-scoped objects?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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