title: Autofac - resolving runtime parameters without having to pass container around
body: <p>I have a simpler "ServiceHelper" class that takes two parameters in the constructor:</p>
  
  <pre><code>public ServiceHelper(ILogger&lt;ServiceHelper&gt; log, string serviceName)
  </code></pre>
  
  <p>(ILogger generic wrapper for NLog that Autofac is providing just fine, and the serviceName is the name of a Windows service to control that I need to provide at runtime.)</p>
  
  <p>I'm having trouble wrapping my head around how to create new instances of this class at runtime passing in different service names, using Autofac. Something like this doesn't work of course since I need to specify different service names at runtime:</p>
  
  <pre><code>builder.RegisterType&lt;ServiceHelper&gt;().As&lt;IServiceHelper&gt;().WithParameter(new NamedParameter("serviceName", null)).InstancePerDependency();
  </code></pre>
  
  <p>From what I've read, its a bad habit to pass the container around and call Resolve manually right (the Service Locator "anti-pattern" the AutoFac warns about), or is it? If I did that then I could do</p>
  
  <pre><code>container.Resolve&lt;ServiceHelper&gt;(new NamedParameter("serviceName", "some service name"));
  </code></pre>
  
  <p>But to even get that far I'm not quite sure how to get Autofac to inject the container into the classes, it would just need to register itself how exactly, like this? And then have my classes require an IContainer in their constructors? (This is in a C# Service using constructor injection)</p>
  
  <pre><code>builder.RegisterType&lt;Container&gt;().As&lt;IContainer&gt;().InstancePerDependency();
  </code></pre>
  
  <p>I read about delegate factories too but that doesn't seem to get away from having to pass the container around. </p>
  
  <p>Really most of my classes that consume the ServiceHelper, just need 1 or 2 ServiceHelpers for specific service names, so its not like I'm making thousands with unexpected serviceName parameters, this is just making my head hurt a little.</p>