对于MassTransit,在设置新的服务总线时,必须声明端点/类型。但是,我试图删除该依赖关系,以便在对使用者进行测试时可以使用回送端点,但一旦投入生产,它将使用实际的msmq端点。
以下是新服务总线的示例设置:
public class ConsumerService
{
IServiceBus _bus;
public void Start()
{
// Initalize Service Bus
_bus = ServiceBusFactory.New(x =>
{
//x.UseMsmq();
x.ReceiveFrom("loopback://localhost/MyQueue");
x.SetConcurrentConsumerLimit(1);
});
_bus.SubscribeConsumer(() => new MyConsumer());
}
public void Stop()
{
_bus.Dispose();
}
}
最佳答案
使用构造函数注入:
public class ConsumerService
{
private readonly IBusInitializer initializer;
public ConsumerService(IBusInitializer initializer)
{
this.initializer = initializer;
}
IServiceBus _bus;
public void Start()
{
// Initalize Service Bus
_bus = ServiceBusFactory.New(x =>
{
this.initializer.initialize(x);
x.SetConcurrentConsumerLimit(1);
});
_bus.SubscribeConsumer(() => new MyConsumer());
}
public void Stop()
{
_bus.Dispose();
}
}
其中
IInitializer
是正确定义的接口,实现可以是:public class LoopbackInitializer : IBusInitializer
{
public void Initialize(WhateverXIs x)
{
x.ReceiveFrom("loopback://localhost/MyQueue");
}
}
public class MsmqInitializer : IBusInitializer
{
public void Initialize(WhateverXIs x)
{
x.UseMsmq();
}
}
在测试或Composition Root中注入所需的实现。
关于unit-testing - MassTransit服务总线配置和单元测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32383124/