My application makes calls out to a bunch of different external API classes. To facilitate this, I have a class for each external API to be called, all of which inherit from a base class which starts like this:
public abstract class ApiBase :
{
protected static HttpClient client = new HttpClient();
protected EntityFrameWorkCredentialObject credential;
public bool AccountSupported(int accountId)
{
using (var context = DBProvider.GetTransientEntityContext())
{
credential = context.EntityFrameWorkCredentialObject
.Where(x => x.AccountId == accountId.FirstOrDefault();
}
return credential != null;
}
}
These objects are created via a factory class, through which it is impossible to get an instance of an object without first checking AccountSupported
. So any instance of a class which inherits this base will have its credential
populated.
Most of these APIs are either public or accept a key as part of the request. However, we now have to deal with a new API which requires a network credential. The documentation for HttpClient says this has to be passed into the object when it's created.
using (var handler = new HttpClientHandler { Credentials = ... })
using (var client = new HttpClient(handler))
{
var result = await client.GetAsync(...);
}
That's obviously going to cause problems for the way my object is built, since it creates an HttpClient
when it's instantiated, and relies on getting the credentials after the fact.
Is there no way to set the credentials on an existing object, or another way out of this without doing a ton of refactoring?