在.net核心项目中按环境加载WCF服务

Ado*_*adh 8 .net c# wcf asp.net-core

我在.NET核心项目中添加WCF时遇到问题.当我以前使用.net时,我可以在web.config中添加多个环境,这样我就可以在运行时加载正确的Web服务(Dev,Rec,Prod).

.net核心项目中的问题,当我将我的WCF服务的引用添加为连接服务时,它创建了一个文件ConnectedService.json,其中包含WCF服务的URL.

{
  "ProviderId": "Microsoft.VisualStudio.ConnectedService.Wcf",
  "Version": "15.0.20406.879",
  "GettingStartedDocument": {
    "Uri": "https://go.microsoft.com/fwlink/?linkid=858517"
  },
  "ExtendedData": {
    "Uri": "*****?singleWsdl",
    "Namespace": "Transverse.TokenService",
    "SelectedAccessLevelForGeneratedClass": "Public",
    "GenerateMessageContract": false,
    "ReuseTypesinReferencedAssemblies": true,
    "ReuseTypesinAllReferencedAssemblies": true,
    "CollectionTypeReference": {
      "Item1": "System.Collections.Generic.List`1",
      "Item2": "System.Collections.dll"
    },
    "DictionaryCollectionTypeReference": {
      "Item1": "System.Collections.Generic.Dictionary`2",
      "Item2": "System.Collections.dll"
    },
    "CheckedReferencedAssemblies": [],
    "InstanceId": null,
    "Name": "Transverse.TokenService",
    "Metadata": {}
  }
}
Run Code Online (Sandbox Code Playgroud)

我的问题如何根据使用的环境加载正确的服务.

注意.

在我的项目中,我没有appsettings也没有web配置.它是一个.net核心类库,在ASP.NET核心应用程序中作为中间件调用.

Ref*_*ael 12

正如我从这篇文章中了解到的,这是微软的建议:

  1. 添加新的类文件
  2. 添加与 service reference.cs 相同的 Namespace
  3. 添加 Partial Class 以扩展引用服务类(在 Reference.cs 中声明)
  4. 和实现 ConfigureEndpoint() 的部分方法(在 Reference.cs 中声明)
  5. ConfigureEndpoint()通过为端点设置新值来实现方法

例子:

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(""));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 在这里,您可以从appsettings.json文件中获取值

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


Ado*_*adh 5

对于解决方案感兴趣的用户,我在每个appseetings。{environment} .json中添加了服务端点。在Service类中,我基于环境变量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;
        });
Run Code Online (Sandbox Code Playgroud)

也许不是最好的,但是效果很好。