我一直在研究实现授权中间件以在消费者级别(而不是消息级别)授权传入消息。 这是此类过滤器的简化版本:
public class ConsumerAuthorizationFilter<TConsumer> : IFilter<ConsumerConsumeContext<TConsumer>>
where TConsumer : class
{
private readonly IAuthorizationService _authorizationService;
public ConsumerAuthorizationFilter(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
public async Task Send(ConsumerConsumeContext<TConsumer> context, IPipe<ConsumerConsumeContext<TConsumer>> next)
{
// some authorization magic using _authorizationService;
}
在 DI 中,在接收端点下,据我所知,需要执行以下操作:
receiveEndpointConfigurator.Consumer<SomeConsumer>(busRegistrationContext, x =>
x.UseFilter(new ConsumerAuthorizationFilter<SomeConsumer>(new _____)));
但是,由于我仍处于应用程序的配置阶段,因此我无法访问 IServiceProvider,因此无法访问 AuthorizationService。
我怎样才能在这里实现我的目标?
谢谢。
附注在我见过的具有 DI 支持的过滤器示例中,过滤器不是基于消费者的,而是基于消息的,并且在配置阶段不需要具体的过滤器,而是在运行时创建的。
我决定直接从 Send() 上下文中的服务提供商获取服务,而不是在 ctor 上。
IServiceScope serviceScope = context.GetPayload<IServiceScope>();
serviceScope.ServiceProvider.GetService<IAuthorizationService>();