title: Add a dependency based on some conditions in AspNetCore
body: <p>I want to add a dependency if some condition is met, but to test the condition I need to make use of <code>IServiceProvider</code>. Is there a good way to do it?</p>
  
  <p>Here is my code but for sure this does not work properly for many reasons but thats what I have achieved so far:</p>
  
  <p>Also I don't want to rebuild the <code>IServiceCollection</code> twice!</p>
  
  <pre><code>public static IServiceCollection AddWithCondition&lt;TInterface, TImplementation&gt;(
      this IServiceCollection collection, 
      Func&lt;IServiceProvider, bool&gt; validateFunc,
      ServiceLifetime lifetime,
      Func&lt;IServiceProvider, TImplementation&gt; factory)
      where TImplementation :  class
  { 
      collection.Add(new ServiceDescriptor(typeof(TInterface), p =&gt; validateFunc(p) ? factory(p) : default(TImplementation), lifetime));
      var descriptorToRemove = collection.FirstOrDefault(d =&gt; d.ServiceType == typeof(TInterface) &amp;&amp; d.ImplementationInstance == default);
      if (descriptorToRemove != null)
          collection.Remove(descriptorToRemove);
      return collection;
  }
  </code></pre>