Home > Software engineering >  Why Restsharp request object won't be renewed in every call
Why Restsharp request object won't be renewed in every call

Time:11-16

This is my RestClientService :

public class RestClientService : IRestClientService
{
    protected readonly RestClient _restClient;
    protected readonly RestRequest _restRequest;

    public RestClientService()
    {
        _restClient = new RestClient();
        _restRequest = new RestRequest();
    }

    public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
    {
        if (await IsPostExist(postId,website))
        {
            _restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
            _restRequest.Method = Method.Post;
            _restRequest.RequestFormat = DataFormat.Json;
            _restRequest.AddJsonBody(new
            {
                post = postId,
                author_name = comment.Author,
                content = comment.Body
            });
            var result = await _restClient.ExecuteAsync(_restRequest);
            return new MessageDTO
            {
                Message = result.Content,
                Status = result.StatusCode.ToString()
            };
        }

        return new MessageDTO
        {
            Message = "Post Not Found",
            Status = "404"

        };
    }
}

I have a list of comments and list of products that I iterate over them and call SendComment method from RestClientService class. The problem is in first time SendComment method called _restRequest object will be get JsonBody and everything is okay but next time this method calls in loop _restRequest object has old data and won't be renewed.

In DI Container I added (Transient) RestClientService

builder.Services.AddTransient<IRestClientService,RestClientService>();

Here is where I used SendComment method in another service.

public async Task<MessageDTO> CreateSendCommentJob(SendCommentConfiguration config)
    {
        var updatedConfig = await _sendCommentConfigurationRepository.Get(config.Id);
        var ConfigDetails = JsonConvert.DeserializeObject<SendCommentConfigurationDetailsDTO>(updatedConfig.Configuration);
        var mappedWebsite = _mapper.Map<Websites>(ConfigDetails.WebsiteInfo);

        if (ConfigDetails.CommentType == "blog")
        {
            var comments = await _uCommentService.GetCommentsByGroupId(ConfigDetails.CommentGroupId);
            var commentCount = 0;

            
            for (int postCount = 0; postCount < ConfigDetails.ProductPerSendCount; postCount  )
            {
                var postId = ConfigDetails.Ids[postCount];

                    while (commentCount < ConfigDetails.CommentsPerProductCount)
                    {
                        var random = new Random();
                        var index = random.Next(comments.Count);

                        var result = await _restClientService.SendComment(mappedWebsite, comments[index], postId);

                        if (result.Status == "Created")
                        {
                            Console.WriteLine($"Comment Index ({index}) at Id ({postId}) submited successfuly...");
                            commentCount  ;
                        }
                        else
                        {
                            Console.WriteLine($"{postId} - {result.Status} - {result.Message}");

                        }
                    }
                ConfigDetails.Ids.Remove(postId);
                commentCount = 0;
            }

        }

        var newConfig = new SendCommentConfiguration
        {
            Id = config.Id,
            Configuration = JsonConvert.SerializeObject(ConfigDetails)
        };

        await _sendCommentConfigurationRepository.Edit(newConfig);

        return new MessageDTO
        {
            Status = "200",
            Message = "Comments Successfuly Sent "
        };
    }

CodePudding user response:

_restClientService.SendComment is called in a loop on the same service instance. As the request instance is a field of the service instance, the same request instance is reused for each call.

As each apple performs a distinct request, each request must use a distinct instance of RestRequest, like :

public class RestClientService : IRestClientService
{
    public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
    {
        if (await IsPostExist(postId,website))
        {
            //Each call, new instances
            var restClient = new RestClient();
            var restRequest = new RestRequest(); 

            restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
            restRequest.Method = Method.Post;
            restRequest.RequestFormat = DataFormat.Json;
            restRequest.AddJsonBody(new
            {
                post = postId,
                author_name = comment.Author,
                content = comment.Body
            });
            var result = await restClient.ExecuteAsync(_restRequest);
            return new MessageDTO
            {
                Message = result.Content,
                Status = result.StatusCode.ToString()
            };
        }

        return new MessageDTO
        {
            Message = "Post Not Found",
            Status = "404"
        };
    }
}
  • Related