title: .NET Core DI resolving keyed services using custom delegate returns null
body: <p>I am struggling with a weird case. I have a .NET Core console application that is setup like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>private static async Task Main(string[] args)
  {
      var runAsService = !(Debugger.IsAttached || args.Contains("console"));
      var builder = new HostBuilder()
          .ConfigureServices((hostContext, services) =&gt;
          {
              services.AddLogging(loggingBuilder =&gt; { loggingBuilder.AddConsole(); });
  
              services.AddGatewayServers();
              services.AddHostedService&lt;GatewayService&gt;();
          });
  
      if (runAsService)
          await builder.RunServiceAsync();
      else
          await builder.RunConsoleAsync();
  }
  </code></pre>
  
  <p>I then have extensions on <code>IServiceCollection</code> that sets up <code>AddGatewayServers()</code> like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static void AddGatewayServers(this IServiceCollection services)
  {
      services.AddTransient&lt;IGatewayServer, Server1&gt;();
      services.AddTransient&lt;IGatewayServer, Server2&gt;();
      services.AddTransient&lt;Func&lt;ServerType, IGatewayServer&gt;&gt;(provider =&gt; key =&gt;
      {
          switch (key)
          {
              case ServerType.Type1: return provider.GetService&lt;Server1&gt;();
              case ServerType.Type2: return provider.GetService&lt;Server2&gt;();
              default: return null;
          }
      });
  }
  </code></pre>
  
  <p>And then in my class I inject the dependency like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>private readonly Func&lt;ServerType, IGatewayServer&gt; _gatewayAccessor;
  
  public GatewayServerCollection(Func&lt;ServerType, IGatewayServer&gt; gatewayAccessor)
  {
      _gatewayAccessor = gatewayAccessor;
  }
  </code></pre>
  
  <p>But when I call the <code>_gatewayAccessor</code> later on in <code>GatewayServerCollection</code> to get me an instance of the <code>IGatewayServer</code> it returns <code>null</code>. I call it like:</p>
  
  <pre class="lang-cs prettyprint-override"><code>var server = _gatewayAccessor(ServerType.Type1);
  </code></pre>
  
  <p>What am i missing?</p>