0

In an Azure Function a static helper class uses RestSharp 106 like this:

public static class InsightlyHelper
{
   private static readonly RestClient RestClient = new RestClient { 
      BaseUrl = new Uri(Environment.GetEnvironmentVariable("InsightlyApiBaseUrl") ?? throw new InvalidOperationException()) 
   };

I switched to RestSharp 107 which uses the HttpClient and changed the code to this:

public static class InsightlyHelper
{
   private static readonly RestClient RestClient = new RestClient(new Uri(Environment.GetEnvironmentVariable("InsightlyApiBaseUrl")));

But this error gets thrown: [Error] Failed to create new SUDB project for insightly project. Error was The type initializer for 'SU_API.Infrastructure.InsightlyHelper' threw an exception.

I have seen the Migration guide

I am thinking of trying to dependency inject RestClient to this helper class and another similar class, anyone tried that? Or other suggestions appreciated.

Bouke
  • 1,531
  • 1
  • 12
  • 21

2 Answers2

0
  • Try adding the below code in csproj file:

<Target Name="PostPublish" BeforeTargets="Publish">
  <Exec Command="move $(PublishDir)\runtimes $(PublishDir)\bin" />
</Target>

  • The exception may occur due to external dependencies "RestSharp.dll" is not added. Try by adding one.
0

Using the dependency injection code pattern worked. I based this off HttpClient best practice in Azure Functions This set of functions contains helper classes (one per external API) instantiated as singletons, injected into functions. Now each of these helper classes gets IHttpClientFactory injected, and passes a HttpClient to an instance of a RestSharp RestClient.

The StartUp.cs looks like

[assembly: FunctionsStartup(typeof(SU_API.Startup))]
namespace SU_API
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
            builder.Services.AddSingleton<IInsightlyHelper, InsightlyHelper>();
        }
    }
}

An example API helper looks like

public class InsightlyHelper : IInsightlyHelper
{
    private readonly HttpClient _httpClient;
    private readonly RestClient RestClient;
    private static readonly RestClientOptions RestClientOptions = new() {BaseUrl = new Uri("https//someuri")};
    public InsightlyHelper(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient();
        RestClient = new RestClient(_httpClient, RestClientOptions);
    }
}

And an API helper gets injected like this

public class InsightlyUpdateMmwLink
{
    private readonly IInsightlyHelper _insightlyHelper;
    public InsightlyUpdateMmwLink(IInsightlyHelper insightlyHelper)
        {
            _insightlyHelper = insightlyHelper;
        }
}