I am designing an interface for 2 distinct implementations as follows:
- Perform operations without client credentials ( for my local applications)
- Perform operations using security token. (for web applications)
Interfaces are as follows :
interface IContactService
{
void Add(Contact c);
void Update(Contact c);
}
interface IProxy
{
string Token { get; set; }
void SetToken(string token);
}
and below are the implementations :
public class ContactBusinessImpl : IContactService
{
private IContactService _contactService;
public ContactBusinessImpl(IContactService contactService) {
_contactService = contactService;
}
public void Add(Contact c)
{
_contactService.Add(c);
}
public void Update(Contact c)
{
_contactService.Update(c);
}
}
public class ContactBusinessProxyImpl : IContactService , IProxy
{
public string Token { get; set; }
public void SetToken(string token)
{
Token = token;
}
public void Add(Contact c)
{
var client = new HttpClient();
client.SetBearerToken(Token);
var stringContent = new StringContent(JsonConvert.SerializeObject(c), Encoding.UTF8, "application/json");
client.PostAsync("api/add", stringContent);
}
public void Update(Contact c)
{
var client = new HttpClient();
client.SetBearerToken(Token);
var stringContent = new StringContent(JsonConvert.SerializeObject(c), Encoding.UTF8, "application/json");
client.PostAsync("api/update", stringContent);
}
}
Earlier I was using token as a parameter for each method (Add(Contact c,string token)) which was not acceptable.
Now I am okay with above approach, but it seems like without SetToken I cant do anything in proxy implementation.
Since I am using DI to instantiate classes for can't go for Adapter pattern like ContactBusinessProxyImpl(string token).
Is there any better approach or pattern can be used here?