lundi 8 février 2016

Should a Rest Client in a mobile app be a singleton?

I'm consuming a REST api within my Xamarin app using RestSharp but am unsure whether I should new up an instance of the client everytime. My code:

I have a simple interface defined as:

public interface IClient
{  
      Task<UserData> GetData();
}

And it's implementation:

public partial class ApiClient : IClient, IDisposable
{
     private readonly RestClient _client;

     public string BaseUrl { get; set; }
     public string SessionId { get; set; }

     public ApiClient(string sessionId, Uri baseUrl)
     {
        BaseUrl = baseUrl.ToString();
        SessionId = sessionId;

        _client = new RestClient(baseUrl);            
    }
}

Currently I'm creating a new instance of of ApiClient every time with the following:

  using (var client = new ApiClient("",new Uri("")))
  {
      ...
  }

But RestClient doesn't implement IDisposable and so I won't have anything to dispose so doesn't really provide anything.

Ideally I would inject this through dependency injection, but this is an existing project and I haven't got round to sorting out DI yet so this is not an option just yet. But if I was (using AutoFac) should I register it as SingleInstance()?

If a new instance is not the recommended way should _client be declared as static and only newed up on it's first call?

Also, as an addition, I believe that this class should only be concerned with returning the classes defined in the service. If my ViewModel needs this data should I have an extra layer in between to map between the two?

Aucun commentaire:

Enregistrer un commentaire