.NET 6中MassTransit与RabbitMQ的IPublishEndpoint依赖注入错误
.NET 6集成MassTransit+RabbitMQ时IPublishEndpoint无法注入的问题
在.NET 6项目中配置MassTransit集成RabbitMQ后,调用接口时出现无法解析MassTransit.IPublishEndpoint服务以激活ItemsController的异常。项目可正常编译,但访问https://localhost:7234/items接口时触发该错误,更换MassTransit.RabbitMQ版本至7.1.3后问题仍存在。
错误信息
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: Unable to resolve service for type 'MassTransit.IPublishEndpoint' while attempting to activate 'Play.Catalog.Service.Controllers.ItemsController'.
相关代码
Program.cs 代码
serviceSettings = configuration.GetSection(nameof(ServiceSettings)).Get<ServiceSettings>(); IServiceCollection services = new ServiceCollection(); services.AddMassTransit(x => { x.UsingRabbitMq((context, configurator) => { var rabbitMQSettings = builder.Configuration.GetSection(nameof(RabbitMQSettings)).Get<RabbitMQSettings>(); configurator.Host(rabbitMQSettings.Host); configurator.ConfigureEndpoints(context, new KebabCaseEndpointNameFormatter(serviceSettings.ServiceName, false)); }); }); services.AddSingleton<IPublishEndpoint>(provider => provider.GetRequiredService<IBusControl>()); services.AddMassTransitHostedService();
ItemsController.cs 代码
[ApiController] [Route("items")] public class ItemsController : ControllerBase { private readonly IRepository<Item> itemRepository; private readonly IPublishEndpoint publishEndpoint; private static int requestCounter = 0; public ItemsController(IRepository<Item> itemRepository, IPublishEndpoint publishEndpoint) { this.publishEndpoint = publishEndpoint; this.itemRepository = itemRepository; } [HttpPost] public async Task<ActionResult<ItemDto>> CreateItemAsync(CreateItemDto createItemDto) { var item = new Item { Name = createItemDto.Name, Description = createItemDto.Description, Price = createItemDto.Price, CreatedDate = DateTimeOffset.UtcNow }; await itemRepository.CreateItemAsync(item); await publishEndpoint.Publish(new CatalogItemCreated(item.Id, item.Name, item.Description)); return CreatedAtAction(nameof(CreateItemAsync), new { id = item.Id }, item); } }
解决方案
问题根源:
- 手动创建独立的
ServiceCollection实例,而非使用.NET 6 Web项目默认的builder.Services,导致注册的服务未被应用程序DI容器加载。 - 手动注册
IPublishEndpoint属于冗余操作,MassTransit的AddMassTransit方法会自动注册IPublishEndpoint、ISendEndpointProvider等核心服务。
修正步骤:
- 移除手动创建的
IServiceCollection services = new ServiceCollection();,改用项目默认的builder.Services(.NET 6中builder由WebApplication.CreateBuilder(args)生成)。 - 删除手动注册
IPublishEndpoint的代码行:services.AddSingleton<IPublishEndpoint>(provider => provider.GetRequiredService<IBusControl>());。 - 统一配置对象获取方式,确保使用
builder.Configuration而非混用configuration和builder.Configuration。
修正后的Program.cs核心代码:
var builder = WebApplication.CreateBuilder(args); var serviceSettings = builder.Configuration.GetSection(nameof(ServiceSettings)).Get<ServiceSettings>(); builder.Services.AddMassTransit(x => { x.UsingRabbitMq((context, configurator) => { var rabbitMQSettings = builder.Configuration.GetSection(nameof(RabbitMQSettings)).Get<RabbitMQSettings>(); configurator.Host(rabbitMQSettings.Host); configurator.ConfigureEndpoints(context, new KebabCaseEndpointNameFormatter(serviceSettings.ServiceName, false)); }); }); builder.Services.AddMassTransitHostedService(); var app = builder.Build(); // 其他中间件配置... app.Run();
内容的提问来源于stack exchange,提问作者Naman Sharma
相关产品推荐
相关产品推荐

