想在 IEndpointRouteBuilder 的扩展方法中检查 IEventBus 接口(Interface) 是否已经注册过,请问如何实现?
尝试下面的代码,却发现即使没有注册,eventBus 的值也不为 null
var eventBus = builder.ServiceProvider.GetService<IEventBus>();
if (eventBus is null)
{
throw new ArgumentNullException(nameof(eventBus));
}
通过 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");
}