Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var gatewayFactory = new GatewayFactory();
- var masterClient = gatewayFactory.CreateMasterClient("someBaseAddress");
- public IMasterService CreateMasterClient(string baseAddress)
- {
- return (MasterServiceClient)CreateHttpClient<IMasterService>($"{baseAddress}api/master/");
- }
- 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");
- }
- IDictionary<Type, Type> mappings; //Populated with all interface to implementation types
- private DalServiceBaseClient CreateHttpClient<T>(string baseAddress) {
- var httpClient = new HttpClient {
- BaseAddress = new Uri(baseAddress)
- };
- var implementationType = mappings[typeof(T)];
- if (implementationType == null)
- throw new ArgumentException("No type exists for the provided interface");
- return (DalServiceBaseClient)Activator.CreateInstance(implementationType, httpClient);
- }
- mappings = new Dictionary<Type, Type>();
- mappings[typeof(IMasterService)] = typeof(MasterServiceClient);
- mappings[typeof(ISlaveService)] = typeof(SlaveServiceClient);
- //...other types;
- IDictionary<Type, Func<HttpClient, DalServiceBaseClient>> mappings; //Populated with all interface to implementation types
- private DalServiceBaseClient CreateHttpClient<T>(string baseAddress) {
- var httpClient = new HttpClient {
- BaseAddress = new Uri(baseAddress)
- };
- var implementationFactory = mappings[typeof(T)];
- if (implementationFactory == null)
- throw new ArgumentException("No type exists for the provided interface");
- return implementationFactory(httpClient);
- }
- mappings = new Dictionary<Type, Func<HttpClient, DalServiceBaseClient>>();
- mappings[typeof(IMasterService)] = (httpClient) => new MasterServiceClient(httpClient);
- mappings[typeof(ISlaveService)] = (httpClient) => new SlaveServiceClient(httpClient);
- //...other types;
- private HttpClient CreateHttpClient(string baseAddress)
- {
- return new HttpClient()
- {
- BaseAddress = new Uri(baseAddress)
- };
- }
- public IMasterService CreateMasterClient(string baseAddress)
- {
- return new MasterServiceClient(
- CreateHttpClient($"{baseAddress}api/master/")
- );
- }
Add Comment
Please, Sign In to add comment