title: asp.net core dependency injection Configure
body: <p>I am looking to inject a kafka producer as a singleton in my app. It currently has two steps required when disposing the instance. First, you must flush the buffer, second call dispose. To increase performance, this should only happen when messages are no longer being processed.</p>
  
  <p>My solution for ASP.NET core, is to use the <code>AddSingleton()</code> method in DI and then use <code>ApplicationLifetime.ApplicationStopping.Register</code> to register a callback that will flush and dispose the producer. I followed the tutorial found here:<a href="https://andrewlock.net/four-ways-to-dispose-idisposables-in-asp-net-core/" rel="nofollow noreferrer">https://andrewlock.net/four-ways-to-dispose-idisposables-in-asp-net-core/</a></p>
  
  <p>putting together a quick test I did the following in my Startup class:</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {         
      var producerConfig = new Dictionary&lt;string, object&gt;
      {
          { "bootstrap.servers", "192.168.99.100:9092" },
          { "client.id", Dns.GetHostName() },
                      { "api.version.request", true }
      };
      services.AddSingleton(new Producer&lt;Null, string&gt;(producerConfig, null, new StringSerializer(Encoding.UTF8)));
     services.AddMvc();
  }
  
  
  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
  {
      loggerFactory.AddConsole();
      app.UseMvc();
      app.UseWebSockets();            
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
  
      }
      lifetime.ApplicationStopping.Register(flushAndDispose, app.ApplicationServices.GetRequiredService&lt;Producer&gt;());
  }
  </code></pre>
  
  <p>but when it runs I get the following error:</p>
  
  <blockquote>
    <p>An exception of type 'System.InvalidOperationException' occurred in
    Microsoft.Extensions.DependencyInjection.Abstractions.dll but was not
    handled in user code: 'No service for type 'Confluent.Kafka.Producer'
    has been registered.'</p>
  </blockquote>