I have a HTTP client factory that creates a separate HTTP proxy instance for each of my services - which are in the cloud. The factory creates each instance on the basis of an interface which the service implements. All of the proxies inherit from a base class called DalServiceBaseClient
which you will see in my code. I don't quite like the way the factory resolves the type to be returned based on the interface.
Here's a simplified version of my code:
Here's how I call my factory to create one of the possible proxies:
var gatewayFactory = new GatewayFactory();
var masterClient = gatewayFactory.CreateMasterClient("someBaseAddress");
Here that same method in GatewayFactory
:
public IMasterService CreateMasterClient(string baseAddress)
{
return (MasterServiceClient)CreateHttpClient<IMasterService>($"{baseAddress}api/master/");
}
And here's the private create method in GatewayFactory
where all of the magic happens:
private DalServiceBaseClient CreateHttpClient<T>(string baseAddress)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri(baseAddress)
};
if (typeof(T) == typeof(IMasterService))
{
return new MasterServiceClient(httpClient);
}
if (typeof(T) == typeof(ISlaveService))
{
return new SlaveServiceClient(httpClient);
}
if (typeof(T) == typeof(IRoleService))
{
return new RoleServiceClient(httpClient);
}
// A lot more ifs..
throw new ArgumentException("No type exists for the provided interface");
}
Since there are a lot of different proxies my method ends up having a lot of if
s and I haven't been able to find a more elegant way of doing this.
T
in the constructor and "automagically" get the right type. \$\endgroup\$ – user34073 Mar 20 '18 at 13:40