title: Winforms IOC Container - Composition Root
body: <p>I've recently been dabbling a bit with IOC Containers (LightInject in my case).</p>
  
  <p>I've been reading that you should only need to use the container ONCE, on startup, and no where else. This is what I'm struggling to understand. If I can only reference the container in a bootstrap/startup method, how is it possible to resolve what I need, elswhere in the project, or at runtime if the class depends on user input.</p>
  
  <p>So In my Traditional Windows Forms App, on Form Load Say, I would Bootstrap Lightinject as per the below code. It's only an arbitrary example, it's more the premise I need to get my head around.</p>
  
  <p>I might be missing something here entirely, or just not getting it. But how am i supposed to resolve dependancies, If i can't use/not supposed to reference or use Container.GetInstance/Resolve/{Choose IOC Syntax Here}, and only in the composition root.</p>
  
  <p>For Instance, Say I have two buttons and a TextBox on my form. The first button gets me an ILoader (below code), and the second button loads up a file viewer (ILoader, below code), whose file name is what is entered into the textbox on the winform.</p>
  
  <p>Without An IOC Container I would do the following (let's just assume its put in the click event)</p>
  
  <p>Button 1 Click Event :</p>
  
  <pre><code>ISplitText MyStringFunc =  new WhateverImplementsIt();
  </code></pre>
  
  <p>Button 2 (gets the file reader based on textbox input)</p>
  
  <pre><code>ILoader MyLoader = new FileReaderImplementation(TextBox1.Text);
  </code></pre>
  
  <p>Using LightInject, I'm surely compelled to do the following:</p>
  
  <p>Button1 Click:</p>
  
  <pre><code>ISplitText Splitter = Container.GetInstance&lt;ISplitText&gt;();
  </code></pre>
  
  <p>Button 2 Click</p>
  
  <pre><code>var LoaderFunc = Container.GetInstance&lt;Func&lt;string, ILoader&gt;&gt;();
  ILoader l2 = LoaderFunc(TextBox1.Text);            
  </code></pre>
  
  <p>Am I Incorrect? In A large project I would have Container.GetInstance, peppered all over the place, in the main form file and elsewhere surely, so how can i only reference the container in ONLY 1 spot, in the form of  bootstrap, am i missing a magic piece of the puzzle?</p>
  
  <p>In all the sample apps I have seen it's all done in one simple console app, in the Main function. All these apps follow the format of:</p>
  
  <pre><code>Container = new Container();
  Container.Register&lt;IFoo,Foo&gt;();
  Container.Register&lt;IBar,Bar();
  
  var Resolved = Container.GetInstance&lt;IFoo&gt;();
  </code></pre>
  
  <p>Well, I understand all that, and it's extremely simple. It's once you start adding a bit of complexity to the app itself, I'm lost as to how to get the instances without making the Container itself public, or static, or accessible in some way,shape or form and then calling Container.GetInstance in a million places (which apparently, is a big no no). PLEASE HELP!
  Cheers,</p>
  
  <p>Chud</p>
  
  <p>PS - I am not concerned about "abstracting the container" itself. so would prefer to only focus on increasing my understanding of the above.</p>
  
  <pre><code>public class BootStrapIOC
  {
      public ServiceContainer Container;
      public BootStrapIOC(ServiceContainer container)
      {
          Container = container;
      }
  
      public void Start()
      {
          Container.Register&lt;ISplitText, StringUtil&gt;();
          Container.Register&lt;string, ILoader&gt;((factory, value) =&gt; new FileViewByFileName(value));
  
  
      }
  }
  
  
  
  //HUH? How can i NOT use the container??, in this case in the button_click
  ILoader Loader = Container.GetInstance&lt;Func&lt;string, ILoader&gt;&gt;();
  ILoader l2 = Loader(TextBox1.Text);            
  ISplitText Splitter = Container.GetInstance&lt;ISplitText&gt;();
  </code></pre>
  
  <p><strong>EDIT #1</strong></p>
  
  <p>OK, so, after re-reading the comments and looking at a few more examples on the interweb, I think I may finally understand it. The issue was (I think) is that i wasn't thinking "higher level" enough. I was trying to resolve my dependancies in my winforms application, AFTER the form had already been constructed,and in the form itself. When in reality, it's too late by then. I wasn't viewing the "form itself" as just another object, which needed it's dependencies injected into it.</p>
  
  <p>So I bootstrap now in my Program.cs:</p>
  
  <pre><code>static class Program
  {
      private static ServiceContainer Container;
  
      /// &lt;summary&gt;
      /// The main entry point for the application.
      /// &lt;/summary&gt;
      [STAThread]
      static void Main()
      {
          Container = new ServiceContainer();
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          BootStrapIOC Strap = new BootStrapIOC(Container);
  
          Strap.Start();
          //This magic line resolves EVERYTHING for me required by the Form
          var form = Container.GetInstance&lt;Form1&gt;();
          Application.Run(form);
          //Application.Run(new Form1());
      }
  }
  </code></pre>
  
  <p>My question now is, Is my line of thinking now correct in terms of winforms. It seems to make more sense, changing my approach to "higher up" the chain and resolving from Program.cs??</p>
  
  <p>Secondly, And I'm not sure if this calls for a new question altogether, please advise as I am an SO noob.</p>
  
  <p>How would I setup a factory to return the correct instance of an object? One of the original comments indicated that that would be a usage in this scenario. Let's use a contrived example.
  Where I needed an object, but don't know which object until run time/user input.</p>
  
  <p>My Idea:</p>
  
  <p>BootStrap
      Container.Register();</p>
  
  <p>Factory Interface and Implementation:
  Let's put some optional parameters in also, as I want to know if this is the correct/best way to do it?</p>
  
  <pre><code>public interface IFileViewerFactory
  {
      ILoader GetFileViewer(string FileName, string Directory = null, bool CreatingDirectory = false);
  }
  
  public class FileViewerFactory:IFileViewerFactory
  {
      public FileViewerFactory() { }
  
      public ILoader GetFileViewer(string FileName, string Directory = null, bool CreatingDirectory = false)
      {
          if (CreatingDirectory == false)
          {
              if (Directory == null)
                  return new FileViewByFileName(FileName);
              else
                  return new FileViewByDirectoryName(Directory, FileName);
          }
          else
              return new FileViewByDirectoryNameCreateDirectoryOptional(Directory, FileName, CreatingDirectory);
      }
  }
  </code></pre>
  
  <p>Form:</p>
  
  <pre><code>public IFileViewerFactory FileViewerFactory { get; set; }
  </code></pre>
  
  <p>Button Click:</p>
  
  <pre><code>ILoader FileLoader = FileViewerFactory.GetFileViewer(TxtBoxFileName.Text);
  </code></pre>
  
  <p>Or:</p>
  
  <pre><code>ILoader FileLoader = FileViewerFacotry.GetFileViewer(TxtBoxFileName.Text,TxtBoxDirectory.Text);
  </code></pre>
  
  <p>So to finish off, my questions are:</p>
  
  <ol>
  <li>Is my new way of "higher level" thinking, and bootstrapping from Program.cs now correct</li>
  <li>How Can I handle optional parameters in LightInject</li>
  <li>Is How I have setup my factory the correct way to do it?</li>
  <li>Let's forget about the Fugliness of the factory and just try to work on the mechanics of the questions :)</li>
  </ol>