【发布时间】:2016-11-15 13:58:07
【问题描述】:
我根据 James Still 的博客文章 Real-World PubSub Messaging with RabbitMQ 创建了一个具有 RabbitMQ 订阅者的 ASP.NET Core MVC/WebApi 站点。
在他的文章中,他使用一个静态类来启动队列订阅者并定义队列事件的事件处理程序。然后,此静态方法通过静态工厂类实例化事件处理程序类。
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
namespace NST.Web.MessageProcessing
{
public static class MessageListener
{
private static IConnection _connection;
private static IModel _channel;
public static void Start(string hostName, string userName, string password, int port)
{
var factory = new ConnectionFactory
{
HostName = hostName,
Port = port,
UserName = userName,
Password = password,
VirtualHost = "/",
AutomaticRecoveryEnabled = true,
NetworkRecoveryInterval = TimeSpan.FromSeconds(15)
};
_connection = factory.CreateConnection();
_channel = _connection.CreateModel();
_channel.ExchangeDeclare(exchange: "myExchange", type: "direct", durable: true);
var queueName = "myQueue";
QueueDeclareOk ok = _channel.QueueDeclare(queueName, true, false, false, null);
_channel.QueueBind(queue: queueName, exchange: "myExchange", routingKey: "myRoutingKey");
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += ConsumerOnReceived;
_channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer);
}
public static void Stop()
{
_channel.Close(200, "Goodbye");
_connection.Close();
}
private static void ConsumerOnReceived(object sender, BasicDeliverEventArgs ea)
{
// get the details from the event
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
var messageType = "endpoint"; // hardcoding the message type while we dev...
// instantiate the appropriate handler based on the message type
IMessageProcessor processor = MessageHandlerFactory.Create(messageType);
processor.Process(message);
// Ack the event on the queue
IBasicConsumer consumer = (IBasicConsumer)sender;
consumer.Model.BasicAck(ea.DeliveryTag, false);
}
}
}
在我现在需要解析消息处理器工厂中的服务而不是仅仅写入控制台时,它的效果很好。
using NST.Web.Services;
using System;
namespace NST.Web.MessageProcessing
{
public static class MessageHandlerFactory
{
public static IMessageProcessor Create(string messageType)
{
switch (messageType.ToLower())
{
case "ipset":
// need to resolve IIpSetService here...
IIpSetService ipService = ???????
return new IpSetMessageProcessor(ipService);
case "endpoint":
// need to resolve IEndpointService here...
IEndpointService epService = ???????
// create new message processor
return new EndpointMessageProcessor(epService);
default:
throw new Exception("Unknown message type");
}
}
}
}
有没有办法访问 ASP.NET Core IoC 容器来解决依赖关系?我真的不想手动启动整个依赖堆栈:(
或者,有没有更好的方法从 ASP.NET Core 应用程序订阅 RabbitMQ?我找到了RestBus,但它没有针对 Core 1.x 进行更新
【问题讨论】:
-
能否将 MessageListener 转换为依赖项,并在需要的地方注入它自己的注入依赖项?
-
我很好奇,下面的答案有帮助吗?
标签: c# asp.net-core dependency-injection rabbitmq service-locator