MediatR-如何发送来自JSON字符串的消息

时间:2019-02-15 15:42:30

标签: json command-pattern mediatr

我试图使用Jimmy Bogard关于MediatR库的示例代码。但是,我希望所有的消息都像JSON字符串一样传入,并且所有的消息都由Dispatch方法处理,而不是能够立即在代码中创建Ping实例。

我有一条类似以下的JSON消息:

{
    "payload": {
        "message": "ping"
    },
    "type": "ping",
            "correlationId" : 123
}

如何通过反射已填充的Ping消息实例化并将其提供给介体的Send方法?

namespace MediatR.Examples
{
    public class Ping : IRequest<Pong>
    {
        public string Message { get; set; }
    }
}



using MediatR;
using Newtonsoft.Json.Linq;
using System;

namespace Web.Commands
{
    public class MediatorDispatcher
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IMediator _mediator;

        public MediatorDispatcher(IServiceProvider serviceProvider, IMediator mediator)
        {
            _serviceProvider = serviceProvider;
            _mediator = mediator;
        }

        public object Dispatch(string json)
        {
            JObject jObject = JObject.Parse(json);
            JToken jToken = jObject["type"];
            if (jToken == null)
            {
                throw new Exception("The parameter type is missing in the JSON string (Pay attention: it is case sensitive).");
            }

            var result = _mediator.Send("HOW TO INSTANTIATE A PING MESSAGE FROM THE JSON STRING????? ");
            return result;
        }
    }
}

0 个答案:

没有答案