vendredi 19 avril 2019

C# Performant method caller attribute usage

I am writing a client library for an API that provides both public and authenticated endpoints. I would like to easily denote which endpoints require authentication using attributes. For instance:

public async Task<ApiResponse> GetPublicData()
{
  var request = CreateRequest( "v1/public" );
  return await _httpClient.GetAsync( request );
}

[RequiresAuthentication]
public async Task<ApiResponse> GetPrivateData()
{
  var request = CreateRequest( "v1/private" );
  return await _httpClient.GetAsync( request );
}

private ApiRequest CreateRequest( string endpoint )
{
   var request = new ApiRequest( endpoint );

   // if (caller has RequiresAuthenticationAttribute)
   //    SignRequest( request, _credentials );

   return request;
}

As far as I am aware, the only way I can access whether or not the caller of CreateRequest has a RequiresAuthenticationAttribute is to create a stack frame, find the method via reflection, and then attempt to get the attribute from the MethodInfo. This can be incredibly slow.

Is there any other way to pass this information into the callee that won't kill performance. I know that the requests will always be limited by the response time of the API, but given that it has to do with financial data, being able to fire off requests as soon as possible is a must, and being able to do it in a clean way that involves attributes instead of manually passing parameters would be very nice.





Aucun commentaire:

Enregistrer un commentaire