asp.net核心依赖注入配置

asp.net core dependency injection Configure

我希望在我的应用程序中将 kafka 生产者作为单例注入。目前在处理实例时需要两个步骤。首先,您必须刷新缓冲区,其次调用 dispose。为了提高性能,这应该只在不再处理消息时发生。

我对 ASP.NET 核心的解决方案是在 DI 中使用 AddSingleton() 方法,然后使用 ApplicationLifetime.ApplicationStopping.Register 注册一个将刷新和处置生产者的回调。我遵循了此处的教程:https://andrewlock.net/four-ways-to-dispose-idisposables-in-asp-net-core/

快速测试我在 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>());
}

但是当它运行时出现以下错误:

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.'

假设也是Producer<T1,T2>来源于Producer

您没有明确向服务集合注册 Producer,因此提供商不知道如何解决它。

services.AddSingleton<Producer>(
    c => new Producer<Null, string>(producerConfig, null, 
        new StringSerializer(Encoding.UTF8)));