Rebus Pub Sub:在订阅者上检索 headers
Rebus Pub Sub: Retrieve headers on subscriber
Headers 使用 Azure 服务总线发布,如下所示:
string content = "body";
await _busPublisher.Activator.Bus.Publish(content, headers);
如何检索 header 和订阅者的内容?
class Handler : IHandleMessages<string>
{
public Handler(IMessageContext messageContext, ILog log)
{
_messageContext = messageContext;
_log = log;
}
public async Task Handle(string message)
{
Console.WriteLine("Handle(string message): {0}", message);
}
}
更新
以下是一种解决方案。这是最好的解决方案吗?
public Handler(IMessageContext messageContext, ILog log)
{
_messageContext = messageContext;
_log = log;
}
public async Task Handle(string message)
{
Console.WriteLine("Handle(string message): {0} ", message);
Console.WriteLine("headers: {0} ", string.Join(' ', _messageContext.Headers));
}
当像下面这样实例化一个 Handler 时,是否可以改用依赖注入?
var Activator = new BuiltinHandlerActivator();
Activator.Register((mc) =>
{
return new Handler(mc, log); //no new?
}
接受 IMessageContext
注入到处理程序的构造函数中是可行的方法:
public class Handler : IHandleMessages<string>
{
readonly IMessageContext messageContext;
public Handler(IMessageContext messageContext, ILog log)
{
this.messageContext = messageContext;
}
public async Task Handle(string message)
{
var headers = messageContext.Headers;
// do stuff
}
}
如果您正在使用 BuiltinHandlerActivator
,您可以像这样注入它:
activator.Register(context => new Handler(context));
或者如果您还需要 IBus
在您的处理程序中:
activator.Register((bus, context) => new Handler(bus, context));
Headers 使用 Azure 服务总线发布,如下所示:
string content = "body";
await _busPublisher.Activator.Bus.Publish(content, headers);
如何检索 header 和订阅者的内容?
class Handler : IHandleMessages<string>
{
public Handler(IMessageContext messageContext, ILog log)
{
_messageContext = messageContext;
_log = log;
}
public async Task Handle(string message)
{
Console.WriteLine("Handle(string message): {0}", message);
}
}
更新
以下是一种解决方案。这是最好的解决方案吗?
public Handler(IMessageContext messageContext, ILog log)
{
_messageContext = messageContext;
_log = log;
}
public async Task Handle(string message)
{
Console.WriteLine("Handle(string message): {0} ", message);
Console.WriteLine("headers: {0} ", string.Join(' ', _messageContext.Headers));
}
当像下面这样实例化一个 Handler 时,是否可以改用依赖注入?
var Activator = new BuiltinHandlerActivator();
Activator.Register((mc) =>
{
return new Handler(mc, log); //no new?
}
接受 IMessageContext
注入到处理程序的构造函数中是可行的方法:
public class Handler : IHandleMessages<string>
{
readonly IMessageContext messageContext;
public Handler(IMessageContext messageContext, ILog log)
{
this.messageContext = messageContext;
}
public async Task Handle(string message)
{
var headers = messageContext.Headers;
// do stuff
}
}
如果您正在使用 BuiltinHandlerActivator
,您可以像这样注入它:
activator.Register(context => new Handler(context));
或者如果您还需要 IBus
在您的处理程序中:
activator.Register((bus, context) => new Handler(bus, context));