Grpc Client - Interceptor - only created once (singleton)
See original GitHub issueI’ve created an interceptor for gRPC clients like it’s described here: https://docs.microsoft.com/en-us/aspnet/core/grpc/clientfactory?view=aspnetcore-3.1 and it’s working fine.
However I want that the inceptor (in my sample below it’s called MyClientInterceptor) is created for each request, at the moment it’s created on the first call and all subsequent calls using the same instance of MyClientInterceptor.
I also registered MyClientIncepter in Unity 5 (I use Microsoft Unity as IOC) as transient, but that doesn’t help because .AddInterceptor() adds the interceptor to a collection instead of resolving it for each request.
Is there some way I can archive this? I want/need to do this because I have to resolve some other instances from the current ioc-container (the child container that’s automatically created for each request).
I’ve registered the interceptor like this (there are also some overloads for interceptor but the beaviour is the same):
services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5001");
})
.AddInterceptor<MyClientInterceptor>();
br
Issue Analytics
- State:
- Created 3 years ago
- Comments:12 (4 by maintainers)
Top GitHub Comments
Hi @JamesNK - just wanted to add Namely’s upvote for making the interceptors scoped to individual requests. We use them for a few things that use information from the current request:
Most of the above are entirely possible if the interceptors are singletons if the service is running in the context of asp .net (whether grpc or mvc) using the
IHttpContextAccessor
. However, we have applications that are based on kafka handlers, and we still want to support things like forwarding request headers from the kafka message. So we’d essentially have to implement the same pattern for accessing the current request, instead of what we do now - inject the current request information using DI inside a request scope. This would be a fair amount of code to change for us, and I’d like to avoid doing so if at all possible.I’ve been able to work around this by registering my own implementation of the
GrpcClientFactory
as transient, while creating and holding a reference to theGrpcChannel
in a singletonGrpcChannelFactory
. We’ve been hesitant to widely deploy this, as we’re not 100% sure if we’re introducing some subtle bug with the channel; but our c-based implementation just kept the channels as singletons, so I’m fairly confident it will not be worse.Yes.
I’ll see whether I can improve this in future versions.