Dynamic endpoints in ServiceReferences.ClientConfig

后端 未结 5 1066
醉话见心
醉话见心 2020-12-16 13:56

When building an app, it is often deployed in different environments (test, dev, prod), and therefore the endpoint addresses are changing. As the ServiceReferences.ClientCon

5条回答
  •  旧巷少年郎
    2020-12-16 14:32

    You can do it during runtime by using the constructor of the WCF client in SL that takes endpoint configuration name and the address. The endpoint configuration name is just "MyService" in your example. The address argument you provide will override the one included in ClientConfig.

    One of the ways to calculate the address of your service during runtime from SL is (I don't guarantee it will work in every environment configuration):

    1. Calculate the root of your site, e.g. by finding the common part of Application.Current.Host.Source.AbsoluteUri and HtmlPage.Document.DocumentUri.AbsoluteUri. Basically, you take characters from the beginning of the shorter path as long as they match case-insensitively characters in the other path.
    2. Append relative path to services if any (it doesn't appear to be the case here).
    3. Append MyService.svc

    Extra Info:

    This may look complicated when you have many services, but it all can be nicely refactored and with a help of Unity made pretty easy to use for any service. For example, I use a helper function which registers a service client with and it's call looks like this: ServicesHelper.RegisterService( "MyService" ); When I need to create an instance of the service client I just resolve MyServiceContractClient type with Unity which uses an injection constructor to create a new instance of my service already properly configured. It can also handle HTTPS situation. Let me know if you need more information on any of that.

提交回复
热议问题