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:
- Add new class file
- Add same Namespace of service reference.cs
- Add Partial Class to expand reference service class (declared in Reference.cs)
- And Partial Method to implement ConfigureEndpoint() (declared in Reference.cs)
- 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(""));
}
}
}
Here, you can take the value from the
appsettings.json
filenew 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.