在.net core Startup.cs ConfigureServices方法中,我将kafka生产者实例注册为单例,然后将该对象作为参数传递给中间层中任何类的构造函数作为接口。在某些情况下,我会“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。” 错误。
services.AddSingleton<IProducer<Null, string>>(provider => new ProducerBuilder<Null, string>(conf).Build());
using (IProducer<Null, string> producer = new ProducerBuilder<Null, string>(conf).Build())
{
services.AddSingleton<IProducer<Null, string>>(provider => producer);
}
这些代码有什么区别。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ... some codes
services.AddSingleton<IProducer<Null, string>>( provider => new ProducerBuilder<Null, string>(conf).Build());
using (IProducer<Null, string> producer = new ProducerBuilder<Null, string>(conf).Build())
{
services.AddSingleton<IProducer<Null, string>>(provider => producer);
}
}
}
错误位置:
public MessageMutation(IHubContext<MessageHub, ITypedHubClient> messageContext, IProducer<Null, string> producer)
{
// some codes...
producer.Produce("my-topic", new Message<Null, string> { Value = message.Value }, handler);
// some codes..
}
由于您要处置生产者,可能会出现错误。单例对象应具有应用程序的生存期(基本上是单例的定义)。
using(IProducer<Null, string> producer = new ProducerBuilder<Null, string>(conf).Build())
是(速记糖)的简写
IProducer<Null, string> producer = null;
try
{
producer = new ProducerBuilder<Null, string>(conf).Build();
// do sth
}
finally
{
producer?.Dispose();
}
但是,当您放置一个对象时,您会释放它的资源,因此以后无法实际使用
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句