title: Using Microsoft Extension Dependency Injection on WinForms in C#
body: <p>My knowledge in DI is very limited.
  I am developing a WinForm project in a solution which every else where in the solution, <a href="https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/" rel="noreferrer">Microsoft Extension Dependency Injection</a> have been used.</p>
  
  <p>I need to pass some dependency into constructor of MainForm:</p>
  
  <pre><code>public partial class MainForm : Form
  {
     public MainForm(ISomeThing someThing)
     {
     }
  }
  </code></pre>
  
  <p>In the Main method, an instance of MainForm is passed to Run method:</p>
  
  <pre><code>[STAThread]
  static void Main()
  {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new MainForm());
  }
  </code></pre>
  
  <p>I tried to use DI to instantiate an instance for Mainform by having a service provider:</p>
  
  <pre><code>private static IServiceProvider ServiceProvider { get; set; }
  </code></pre>
  
  <p>and then assigning to it an object as follows:</p>
  
  <pre><code>static void ConfigureServices()
  {
     var services = new ServiceCollection();
     services.AddTransient&lt;ISomeThing, SomeThing&gt;();
     ServiceProvider = services.BuildServiceProvider();
  }
  </code></pre>
  
  <p>And then call <code>ConfigureServices()</code> in <code>Main()</code> as follows:</p>
  
  <pre><code>static void Main()
  {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     ConfigureServices();
     Application.Run(ServiceProvider.GetService(MainForm));
  }
  </code></pre>
  
  <p>However, I get a compilation error: "<strong>MainForm is a type, which is not valid in the given context</strong>"</p>
  
  <p>I found the following links which uses similar approach using <a href="http://simpleinjector.readthedocs.io/en/latest/windowsformsintegration.html" rel="noreferrer">SimpleInjector</a> or <a href="https://stackoverflow.com/questions/17436334/how-to-use-di-when-spawning-new-windows-forms-downstream">Unity</a>
  but I do not know how to use this with this kind of DI? or I have to use other DI?</p>
  
  <p>Thanks</p>