Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a pattern for initializing objects created via a DI container
    primarykey
    data
    text
    <p>I am trying to get Unity to manage the creation of my objects and I want to have some initialization parameters that are not known until run-time:</p> <p>At the moment the only way I could think of the way to do it is to have an Init method on the interface.</p> <pre class="lang-cs prettyprint-override"><code>interface IMyIntf { void Initialize(string runTimeParam); string RunTimeParam { get; } } </code></pre> <p>Then to use it (in Unity) I would do this:</p> <pre class="lang-cs prettyprint-override"><code>var IMyIntf = unityContainer.Resolve&lt;IMyIntf&gt;(); IMyIntf.Initialize("somevalue"); </code></pre> <p>In this scenario <code>runTimeParam</code> param is determined at run-time based on user input. The trivial case here simply returns the value of <code>runTimeParam</code> but in reality the parameter will be something like file name and initialize method will do something with the file.</p> <p>This creates a number of issues, namely that the <code>Initialize</code> method is available on the interface and can be called multiple times. Setting a flag in the implementation and throwing exception on repeated call to <code>Initialize</code> seems way clunky.</p> <p>At the point where I resolve my interface I don't want to know anything about the implementation of <code>IMyIntf</code>. What I do want, though, is the knowledge that this interface needs certain one time initialization parameters. Is there a way to somehow annotate(attributes?) the interface with this information and pass those to framework when the object is created?</p> <p>Edit: Described the interface a bit more.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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