Best practice use of JsonServiceClient

Can i ask a simple question regarding best practice of using JsonServiceClient, as I’ve not used clients before.

Should a new JsonServiceClient be created every time or reused, e.g.

using (var client = new JsonServiceClient ("https://url"))
{
  client.Get(new Poco());
  :
}

or

container.Register<MyClientFactory>(...);

:

var client = TryResolve<MyClientFactory>();
client.Get(new Poco());

Is there much overhead in creating a new client, or can the the client be stored and reused, potentially across multiple threads (I understand the cookies are shared)?

If you don’t care about shared cookies you should be able to use the same instance of JsonServiceClient across multiple threads because JsonServiceClient creates new HttpWebRequest for every request and does not share members except of CookieContainer.

If you create JsonServiceClient every time with using keyword the overhead will be minimal. it’s only initialization of some properties in constructor but comparing to latter methods of creating HttpWebRequest and sending/receiving data over network their times can be ignored. You can create simple benchmarking for your task and your data to compare times when JsonServiceClient is created every time and when it’s created once to see the numbers in your particular case.

So you can use any of these two methods but I personally would prefer to use the method with using keyword, because in this case it’s easy to see and control request scope and be sure that there is no mess with cookies.

1 Like

So each time you need to access a service what do you do with the Authenticate permission ?

Once you authenticate the JsonServiceClient is populated with the Session Cookies which can be used to make authenticated requests.

If needed you can copy client.CookieContainer to another .NET HttpWebRequest to make authenticated requests, e.g. sharing cookies with HTTP Utils:

client.Post(new Authenticate { ... });

var response = BaseUrl.CombineWith("/path/to/secure/service")
    .GetJsonFromUrl(requestFilter: req => req.CookieContainer = client.CookieContainer)
    .FromJson<MySecureResponse>();
2 Likes