我正在研究 MassTransit 和 ASP.NET Core、依赖注入(inject)并成功实现了一些有用的东西。我计划使用 Kestrel Web 服务器。
所以我必须在 Startup.cs
中以这种方式配置我的 ASP.NET 核心项目。
public void ConfigureServices(IServiceCollection services) {
...
var bus = Bus.Factory.CreateUsingRabbitMq(sbc => {
var host = sbc.Host(new Uri(address), h => {
h.Username("guest");
h.Password("guest");
});
});
services.AddSingleton<IBus>(bus);
services.AddScoped<IRequestClient<GetTagRequest, GetTagAnswer>>(x =>
new MessageRequestClient<GetTagRequest, GetTagAnswer>(x.GetRequiredService<IBus>(), new Uri(address + "/gettagrequest"), timeOut));
bus.Start(); // <= ok. how is the bus supposed to stop ?
...
虽然这工作正常,但没有教程提到任何有关在 ASP.NET Core 项目中设置 bus.Stop()
的内容。我在 MassTransit 文档中读到,正在运行的公交车可能会阻止正常下车。
- 这是 Kestrel 网络服务器的主要问题吗?我读过有关过程回收的信息,但我担心正在运行的公共(public)汽车会损害这一点。
- 我可以在 ASP.NET Core 项目中的哪个位置放置
bus.Stop()
?
最佳答案
您可以使用 ApplicationLifetime
事件。只需将您的 IBus
对象类级别设为变量即可。
public class Startup
{
private IBus _bus;
public void ConfigureServices(IServiceCollection services) {
/* ... */
_bus = Bus.Factory.CreateUsingRabbitMq ...
/* ... */
}
public void Configure(IApplicationLifetime appLifetime)
{
appLifetime.ApplicationStarted.Register(() => _bus.Start());
appLifetime.ApplicationStopping.Register(() => _bus.Stop());
}
}
关于c# - 如何停止 ASP.NET Core 服务器中的 MassTransit 总线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741170/