通过 github 上的 issue Add ability to detect if a service is registered in the DI container,发现这个 PR Add support for IServiceProviderIsService,知道了 IServiceProviderIsService
接口,使用这个接口解决了
var serviceCheck = builder.ServiceProvider.GetRequiredService<IServiceProviderIsService>();
if (!serviceCheck.IsService(typeof(IEventBus)))
{
throw new InvalidOperationException($"{nameof(IEventBus)} has not been registered");
}