load WCF service by environment in .net core project

I am using .Net Core 3.1, this is my way when I call WCF Service.

var sUserClientRemoteAddress = _configuration.GetValue<string>("WCFRemoteAddress:UserClient");
UserClient userService = new UserClient(UserClient.EndpointConfiguration.CustomBinding_IUser, sUserClientRemoteAddress);

First, Get the endpoint remote address from appsettings.json

Second, Call web service client using that address in CTOR WCF Client Class parameter

Thanks in advance.


As I understand from this article, this is Microsoft's recommendation:

  1. Add new class file
  2. Add same Namespace of service reference.cs
  3. Add Partial Class to expand reference service class (declared in Reference.cs)
  4. And Partial Method to implement ConfigureEndpoint() (declared in Reference.cs)
  5. Implement ConfigureEndpoint() Method by Setting a new value for Endpoint

Example:

namespace Your_Reference_Service_Namespace
{
    public partial class Your_Reference_Service_Client
    {
        static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials)
        {
            serviceEndpoint.Address = 
                new System.ServiceModel.EndpointAddress(new System.Uri("http://your_web_service_address"), 
                new System.ServiceModel.DnsEndpointIdentity(""));
        }
    }
}
  1. Here, you can take the value from the appsettings.json file

    new System.Uri(configuration.GetValue("yourServiceAddress")


For whom are interested by the solution I added an endpoint for my service in each appseetings.{environment}.json and in Service class I inject new Instance of my service based on the environment variable ASPNETCORE_ENVIRONMENT

   services.AddTransient<Transverse.TokenService.ITokenService>(provider =>
        {
            var client = new Transverse.TokenService.TokenServiceClient();
            client.Endpoint.Address = new System.ServiceModel.EndpointAddress(Configuration["Services:TokenService"]);
            return client;
        });

Maybe is not the best but it works fine.