Предложение о том, как реализовать условную зависимость? - PullRequest
1 голос
/ 09 марта 2019

У меня есть два класса, реализующих интерфейсы. Оба класса выполняют функции поиска места. Также в обоих конструкторах classe есть общая функциональность в зависимости от классов

Google: IGoogle

public NearBySearch(IWebPortalApiClient webPortalApiClient)
    {
        var serverString = ConfigHelper.GetAppSetting(ConfigConstants.APIServerType);
        var server = (WebPortalServer)Enum.Parse(typeof(WebPortalServer), serverString, true);
        this._webPortalApiClient = webPortalApiClient;
        this.GoogleKey = $"&key={ConfigHelper.GetAppSetting(ConfigConstants.Googlekey)}";
        this._webPortalApiClient.Init(server);
    }

Визг: IYelp

public BusinessSearch(IWebPortalApiClient webPortalApiClient)
    {
        var serverString = ConfigHelper.GetAppSetting(ConfigConstants.APIServerType);
        var server = (WebPortalServer)Enum.Parse(typeof(WebPortalServer), serverString, true);
        this._webPortalApiClient = webPortalApiClient;
        this._webPortalApiClient.AccessToken = ConfigHelper.GetAppSetting(ConfigConstants.YelpApiKey);
        this._webPortalApiClient.Init(server, this._webPortalApiClient.AccessToken);
    }

В случае Google мы должны отправить ключ в качестве параметра запроса, где, как в Yelp, мы должны отправить ключ в качестве заголовка авторизации

В API-контроллере я ввожу оба

* 1013 igoogle *

private IYelpController _yelpController;
    private IGoogleController _googleController;

    public PlaceSearchController(IYelpController yelpController, IGoogleController googleController)
    {
        this._yelpController = yelpController;
        this._googleController = googleController;
    }

Функция, которую мы вызываем в API, похожа на

[HttpGet]
    public async Task<IHttpActionResult> GetAllBusiness(int web, decimal latitude, decimal longitude, string radius = null)
    {
        try
        {
            if (web == (int)PlaceSearch.Yelp)
            {
                var result = await _yelpController.GetAllBusiness(latitude, longitude, radius);
                var response = new Response<Common.Models.Yelp.Yelp>(ResponseConstants.Success, ResponseConstants.SuccessMessage, result);
                return Ok(response);
            }
            else if(web == (int)PlaceSearch.Google)
            {
                if(radius == null)
                {
                    throw new Exception();
                }

                var result = await _googleController.GetAllNearByPlaces(latitude, longitude, radius);
                var response = new Response<Common.Models.Google.Google>(ResponseConstants.Success, ResponseConstants.SuccessMessage, result);
                return Ok(response);
            }

            throw new Exception();
        }
        catch (Exception ex)
        {
            var response = new Response<Object>(ResponseConstants.Forbidden, ResponseConstants.FailureMessage, null);
            return Ok(response);
        }
    }

Проблема, с которой я столкнулся, заключается в том, что функция ниже вызывается в конструкторе

public IWebPortalApiClient Init(WebPortalServer server, string accessToken = null)
    {
        WebPortalServer = server;
        AccessToken = accessToken;
        return this;
    }

Когда Yelp выполняется, токен передается, как и ожидалось, но в то же время мы не передаем токен доступа в Google, который устанавливает токен доступа на ноль.

Из-за этой проблемы я не могу вызвать API Yelp, так как он не находит токен доступа.

Есть ли способ, которым мы вводим зависимость на условной основе. Для этого мы используем Unity Container.

Клиент веб-портала

public class WebPortalApiClient : IWebPortalApiClient
{
    public WebPortalServer WebPortalServer { get; set; }
    public string AccessToken { get; set; }

    private string ServerUrl
    {
        get
        {
            switch (WebPortalServer)
            {
                case WebPortalServer.Dev:
                    return null;
                case WebPortalServer.QA:
                    return null;
                case WebPortalServer.Demo:
                    return null;
                case WebPortalServer.Production:
                    return null;
                case WebPortalServer.Localhost:
                    return "http://localhost:63695/";
                case WebPortalServer.Integration:
                    return null;
                case WebPortalServer.UAT:
                    return null;
                default:
                    throw new ArgumentOutOfRangeException();

            }
        }
    }

    public async Task<HttpContent> InvokeApi(string path, HttpAction action, HttpContent content = null, TimeSpan? overrideTimeout = null, string externalServer = null)
    {

        var sUrl = externalServer == null ? ServerUrl : externalServer;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(sUrl);
            if (overrideTimeout.HasValue)
            {
                client.Timeout = overrideTimeout.Value;
            }
            //this.Log("Connecting to {0} Api at {1}".Fmt(WebPortalServer, ServerUrl));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response;

            switch (action)
            {
                case HttpAction.Get:
                    response = await client.GetAsync(path);
                    break;
                case HttpAction.Post:
                    response = await client.PostAsync(path, content);
                    break;
                case HttpAction.Put:
                    response = await client.PutAsync(path, content);
                    break;
                case HttpAction.Delete:
                    response = await client.DeleteAsync(path);
                    break;
                default:
                    throw new ArgumentOutOfRangeException("action", action, null);
            }

            return response.IsSuccessStatusCode ? response.Content : null;
        }
    }

    public IWebPortalApiClient Init(WebPortalServer server, string accessToken = null)
    {
        WebPortalServer = server;
        AccessToken = accessToken;
        return this;
    }
}
...