简体   繁体   中英

Could not send list of custom objects via Publish method of IPublishEndpoint in MassTransit (Messages types must not be System type)

Note this is not a duplicate question of MassTransit messages types must not be System types exception .

I am using RabbitMQ version 8.0.2 in Asp.NET Core Web API (.Net 6) . I can publish a custom object successfully by using Publish method of IPublishEndpoint , however, whenever I try to send publish List of the object I get this error:

System.ArgumentException: Messages types must not be System type

Here is the full sample:

public class WeatherForecastController : ControllerBase
    {
        private readonly IPublishEndpoint _publishEndpoint;
        public WeatherForecastController(IPublishEndpoint publishEndpoint)
        {
            _publishEndpoint = publishEndpoint;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public async Task<IEnumerable<WeatherForecast>> Get()
        {
            var data = Enumerable.Range(1, 3).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                myDictionary = new Dictionary<string, string>
                                {
                                    { "key1", "value1" },
                                    { "key2", "value2" }
                                }
            }).ToList();

            //Error!
            await _publishEndpoint.Publish<IList<WeatherForecast>>(data);

            //Working 
           //await _publishEndpoint.Publish<WeatherForecast>(data.FirstOrDefault());
            
            return data;
        }
    }

And in Program.cs

builder.Services.AddMassTransit(options => {
    options.UsingRabbitMq((context, cfg) =>
    {
        cfg.Host(new Uri("rabbitmq://localhost:5672"), h =>
        {
            h.Username("guest");
            h.Password("guest");
        });
    });
});

Why I can't use IList with Publish methods?

You can't use IList<T> with Publish because it isn't supported. There are some PublishBatch extension methods that enumerate the list and call Publish for each element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM