title: Caching dependencies, or copy them at injection?
body: <p>I have some configuration objects initialized by Autofac.
  They are quite heavy to load (read the configuration file, deserialize it, verify some things, map the matching POCO object...).<br />
  But performances are fine because the registered object is declared as <code>.SingleInstance()</code>, so it's loaded only once, the first time it is injected somewhere, and after that the same instance is always used.</p>
  <pre><code>        builder.Register(c =&gt; _settingsReader.LoadSection(thing)) // Read and map object
              .OnActivated(t =&gt;
              {
                  // Do some checks on it to see if settings appear to be correct
              })
              .As(settingInterface)
              .SingleInstance();
  </code></pre>
  <p>But, these objects can be modified later (deliberately, or by accident), and as they are singletons the whole application will be affected if it happens.</p>
  <p>The ability to be both able to update the initial singleton itself (to globally override defined settings) AND to update the local copy (to change the behavior of the object where the setting class have been injected, but not of the whole application) would also be interesting.</p>
  <p>I thought about two possibilities :</p>
  <ul>
  <li>Ask Autofac to inject &quot;copy&quot; of objects, instead of the same instance, but I don't think there is a such &quot;caching / copy&quot; feature in it and I would lose the abilility to manipulate the singleton, or</li>
  <li>Use Automapper to deep-copy the object when it's injected, and store the copy in the dependant object instead of the original object. I'm fine with automapper (and the objects are very light so performance would not be an issue), but adding the copy for each injected property will burden either my Autofac configuration, or my objects themselves depending of where I place the &quot;copy this object&quot; code.</li>
  </ul>
  <p>To use the Automapper idea, I'd have to do something like :</p>
  <pre><code>        builder.RegisterType&lt;MyConsumingClass&gt;()
              .WithParameter(
                  new ResolvedParameter(
                      (pi, ctx) =&gt; pi.ParameterType == typeof(IMySettingClass),
                      (pi, ctx) =&gt;
                      {
                          var mapper = ctx.Resolve&lt;Mapper&gt;();
                          return mapper.Map&lt;ConcreteSettingClass&gt;(ctx.Resolve&lt;IMySettingClass&gt;());
                      }))
              .As&lt;IMyConsumingClass&gt;();
  </code></pre>
  <p>Instead of just</p>
  <pre><code>        builder.RegisterType&lt;MyConsumingClass&gt;().As&lt;IMyConsumingClass&gt;();
  </code></pre>
  <p>(the previous code have not been tested, it's just here for example purpose)</p>
  <p>I would really appreciate to have suggestions on best ways to handle this.</p>