grpc/grpc-dotnet

[Question] IGrpcServiceActivator.Create(IServiceProvider serviceProvider): possible to get ServerCallContext there?

osexpert opened this issue · 2 comments

Trying to create a custom activator so I can extract some data from ServerCallContext headers and pass into service ctor (service created on every request).

		public GrpcActivatorHandle<TGrpcService> Create(IServiceProvider serviceProvider)
		{
			// Need ServerCallContext here
		}

I can see where Create is called, ServerCallContext is available, but is not being sent to Create:

public async Task Invoke(HttpContext httpContext, ServerCallContext serverCallContext, IAsyncStreamReader<TRequest> requestStream, IServerStreamWriter<TResponse> responseStream)
{
	if (_pipelineInvoker == null)
	{
		GrpcActivatorHandle<TService> serviceHandle = default(GrpcActivatorHandle<TService>);
		try
		{
			serviceHandle = base.ServiceActivator.Create(httpContext.RequestServices); // send serverCallContext here?
			await _invoker(serviceHandle.Instance, requestStream, responseStream, serverCallContext);
		}

Is it possible to extend Create to send ServerCallContext? Or some other way?

You could try setting up IHttpContextAccessor in your app, using it to get an HttpContext then the ServerCallContext from the HttpContext.

Like this?

IHttpContextAccessor _accessor;
var context = _accessor.HttpContext?.Features.Get<IServerCallContextFeature>()?.ServerCallContext;

I will try, seems like it should work. I see some discourage use of IHttpContextAccessor and its kind of cluncy, so I would still put it on the wishlist, if possible.