1

I have an API client generated by NSwagStudio. My constructor for one of my endpoints looks like this:

 private string _baseUrl = "http://localhost:11957";
    private System.Net.Http.HttpClient _httpClient;
    private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;

    public AccountClient(System.Net.Http.HttpClient httpClient)
    {
        _httpClient = httpClient; 
        _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(() => 
        {
            var settings = new Newtonsoft.Json.JsonSerializerSettings();
            UpdateJsonSerializerSettings(settings);
            return settings;
        });
    }

   public string BaseUrl 
        {
            get { return _baseUrl; }
            set { _baseUrl = value; }
        }

About 5 of these clients are generated. Obviously for production environments I want my API endpoint to be different. At the moment I use compiler hints (#if debug) to set either local or production endpoints.

Because all 5 of these clients get dependency injected as a singleton, is there an easy way to configure the BaseUrl for all 5 of these clients to use? I know I can just set BaseUrl early on across all 5 clients but I feel like there's gotta be an easier way to accomplish that then just copy pasta.

Thanks!

EDIT: In NSwagStudio I've tried to create a "configuration class" but couldn't easily see how to use it or apply it to this scenario.

Lewis Cianci
  • 926
  • 1
  • 13
  • 38

1 Answers1

1

You can set the serverHost to “.” so that the url is a ctor parameter

Rico Suter
  • 11,548
  • 6
  • 67
  • 93
  • Okay cool, but how I would I use that in dependency injection where I can only specify an interface and a concrete implementation? – Lewis Cianci May 04 '19 at 02:47
  • There are other di registration options where you can specify the url param – Rico Suter May 04 '19 at 08:30
  • Okay. I'm only used to using dependency injection by using an interface, and then specifying the implementation of that interface. With the generated nswag client I don't get an interface generated.... so I can't see how to inject it :(. Am I getting the wrong end of the stick here? I also can't make sense of how the "configuration object" works for nswag clients. The documentation talks about it but not really how to use it per se. – Lewis Cianci May 08 '19 at 06:56
  • 1
    So this was my fault, I missed the huge "generate interfaces" button in NSwagStudio. Now I'm generating interfaces and using DI the normal way. It works fine (On Xamarin Forms too!). It is so, so good, thank you for NSwagStudio :) – Lewis Cianci May 08 '19 at 07:20