confluentinc / confluent-kafka-dotnet

Confluent's Apache Kafka .NET client
https://github.com/confluentinc/confluent-kafka-dotnet/wiki
Apache License 2.0
2.78k stars 847 forks source link

Creating generic Producer throws argument null exception #2160

Open Pablovide opened 6 months ago

Pablovide commented 6 months ago

Description

I need to dynamically create generic producers for my development, but ProducerBuilder throws ArgumentNullException on Build(). Is it doable or am I implementing it wrong?

How to reproduce

My application framework is netstandard 2.1, nuget version 2.3.0

I have created a simple console app to reproduce it (in this case it is net8):

using Confluent.Kafka;

var config = new ProducerConfig
{
    BootstrapServers = "localhost:9093",
};

var producer = new MessageProducer<SampleMessage>(config);

producer.Produce(new SampleMessage{Value = "Hello World!" }, "sample-message-worker");

Console.ReadLine();

class MessageProducer<TMessage> where TMessage : class
{
    private readonly IProducer<Null, TMessage> _producer;
    public MessageProducer(ProducerConfig pconfig)
    {

        _producer = new ProducerBuilder<Null,TMessage>(pconfig).Build();
    }

    public void Produce(TMessage message, string topic)
    {
        var msg= new Message<Null, TMessage>() { Value = message};
        _producer.Produce(topic, msg);
    }

}

class SampleMessage
{
    public string Value { get; set; }
}

Checklist

Please provide the following information:

anchitj commented 4 months ago

Can you provide more details on the exception with the stacktrace? You can refer our examples https://github.com/confluentinc/confluent-kafka-dotnet/blob/a67bd6c06b7eef4293e6476d9ff6f3e93f0e4cd9/examples/JsonSerialization/Program.cs#L141 to how to use ProducerBuilder correctly.

ksdvishnukumar commented 1 month ago

@Pablovide I see that erroendue to Serializer..

For the Custom model you need to register the SetSerializer method with the Custom Serializer class derived from ISerializer interface.

That should work for you if still you have the issue.