Configure asp.net core Configure dependency
I want to enter as one single in my app kafka app. It currently takes two steps to delete an instance. First, you must flush the buffer, remove the second call. To improve performance, this should only happen when messages are no longer processed.
My solution for ASP.NET core is to use a method AddSingleton()
in DI and then use ApplicationLifetime.ApplicationStopping.Register
to register a callback that will hide and remove the producer. I followed the tutorial found here: https://andrewlock.net/four-ways-to-dispose-idisposables-in-asp-net-core/
to put together a quick test, I did the following in my Startup class:
public void ConfigureServices(IServiceCollection services)
{
var producerConfig = new Dictionary<string, object>
{
{ "bootstrap.servers", "192.168.99.100:9092" },
{ "client.id", Dns.GetHostName() },
{ "api.version.request", true }
};
services.AddSingleton(new Producer<Null, string>(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<Producer>());
}
but when it starts I get the following error:
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 "was registered.
source to share
It is also assumed that it is Producer<T1,T2>
obtained fromProducer
you have not explicitly registered the service Producer
in the collection so the provider would not know how to resolve it.
services.AddSingleton<Producer>(
c => new Producer<Null, string>(producerConfig, null,
new StringSerializer(Encoding.UTF8)));
source to share