title: Using Castle Windsor child containers to resolve a type with a specific instance
body: <p>I'm currently using Castle Windsor's child container functionality to override the registration of a particular type with a specific instance in a factory method. I am using the child containers purely so that the registration is temporary for a single resolution - in other words, I don't want the registration to affect all resolutions for that type.</p>
  
  <p>Perhaps some code will explain what I mean.</p>
  
  <p>I have a Func which acts as a factory <code>Func&lt;IReportCategory, IReportCategoryViewModel&gt;</code> - I give it an implementation of an IReportCategory and it returns a new instance of an IReportCategoryViewModel. (IReportCategoryViewModel has a dependency on IReportCategory).</p>
  
  <p>This is registered with Castle Windsor as follows:</p>
  
  <pre><code>        container.Register(
              Component.For&lt;Func&lt;IReportCategory, IReportCategoryViewModel&gt;&gt;().Instance(
                  category =&gt; ResolveCategoryViewModelFactory(container, category)));
  </code></pre>
  
  <p>Where <code>ResolveCategoryViewModelFactory</code> is implemented as follows:</p>
  
  <pre><code>    private CategoryViewModel ResolveCategoryViewModelFactory(IWindsorContainer container, IReportCategory category)
      {
          using (IWindsorContainer childContainer = new WindsorContainer())
          {
              childContainer.Register(Component.For&lt;IReportCategory&gt;().Instance(category));
              container.AddChildContainer(childContainer);
  
              return childContainer.Resolve&lt;IReportCategoryViewModel&gt;();
          }
      }
  </code></pre>
  
  <p>What the above method achieves is the resolution of IReportCategoryViewModel, injecting the specific instance of IReportCategory as a dependency. If IReportCategoryViewModel has other dependencies that need satisfying, then these get automatically injected by the container.</p>
  
  <p>I can subsequently use the Func as follows:</p>
  
  <pre><code>public class Test
  {
      private readonly Func&lt;IReportCategory, IReportCategoryViewModel&gt; factory;
  
      public Test(Func&lt;IReportCategory, IReportCategoryViewModel&gt; factory)
      {
          this.factory = factory;
      }
  
      public void ResolveTest()
      {
          // Create a category (note: this would probably be resolved from the container in some way)
          IReportCategory category = new ReportCategory();
  
          // Call into the factory to resolve the view model
          IReportCategoryViewModel vm = factory(category);
      }
      ...
  </code></pre>
  
  <p><strong>Question:</strong> Does this seem like a suitable thing to do? From the impression I get, child containers are not recommended in Castle Windsor - is there another way of achieving the same result?</p>
  
  <p>Thanks for your help.</p>