在.NET中管理多个服务引用的最佳方法 [英] Best way to manage multiple Service References in .NET

查看:38
本文介绍了在.NET中管理多个服务引用的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有15个WCF/ASMX服务参考的C#ASP.NET项目.每个服务都部署到三台不同的服务器上. test staging live .

通常我们需要将这些服务引用的URL更改为不同的服务器,以便能够使用具有正确实现和数据的正确服务进行调试.

在管理这些服务引用时,我很难保持URL同步.创建服务参考 FooService 时,它将URL存储在三个单独的文件中:

  • FooService.disco
  • configuration.svcinfo
  • Reference.svcmap

通过在 Web.config 中使用URL创建一个 endpoint 节点.

如果我在Web.config中更改端点URL并重建项目,则它不会更新其他文件中的URL,因此它不同步.因此,当我右键单击 FooService 并单击 Update Service Reference 时,它不使用存储在 Web.config 中的URL,它将使用其他文件中的URL.

因此,唯一的方法是右键单击 FooService ,然后单击 Configure Service Reference ,然后输入新的URL.但这并不总是可行的,因为有时它会在Web.config中创建一个名为 FooService1 的新节点,因此在运行我的应用程序时出现错误,提示有两个端点相同的实例./p>

通常我需要浏览Web.config并删除端点的重复项,这非常令人沮丧.

经常更改服务的URL时,管理多个WCF服务引用的最佳方法是什么?

解决方案

首先是概述

我处理它的方法是不通过Visual Studio添加服务引用.我所拥有的是每个服务在解决方案中都有其自己的Proxy项目,使用简单的单行批处理文件创建代理.然后将这些中的每一个作为香草"包含在网站中.参考.端点是在Web配置中手动配置的.我有三个部署选项:调试(本地),登台和发布.在web.config级别,不同的地址由

我只有2个服务,因此我的设置非常简单,只有15个设置会涉及很多工作,但是从长远来看,它将节省您的头部疼痛.

实施

首先备份所有内容!

还可以方便地保存现有web.config的副本,以帮助稍后配置端点.

还请注意,如果您的解决方案位于名称中带有空格的路径中,则批处理文件将不起作用.VS将项目放置在默认位置.我所有的项目都采用以下结构 C:\ Source \ vs2008 \ C:\ Source \ vs2010 \ 等.我将看看是否可以找到更好的解决方案为此.

0以管理员身份运行VisualStudio

从开始菜单中右键单击Visual Studio,然后选择以管理员身份运行".我们需要这样做,因为VS会写入文件.

1删除现有的服务引用

您不需要任何帮助.

2添加代理项目

现在执行此操作意味着您只需配置一次test | staging | live的解决方案即可.

从文件"菜单中选择添加"然后新建项目"并从下面的"Visual C#"开始放大选择类库".并把它命名为明智的.在此示例中,我将使用 FooService.proxy .重命名类文件,在此示例中,我将使用 FooService_proxy.cs .

向项目添加以下引用:

为每个服务添加一个项目.我们将稍后回来并更新这些项目.

3配置解决方案以处理测试|登台|实时

我假设您在本地计算机上开发asp.net网站时使用了 test .

打开配置管理器"通过在构建配置"下拉菜单中选择它.

在活动解决方案配置"下下拉菜单中选择新建"

对于名称,我建议暂存"并检查创建新项目配置"复选框.

在解决方案资源管理器中,右键单击Web.Config,然后选择添加配置转换".这将为暂存web.config转换添加一个新文件.单击扩展器箭头,您将看到三个子文件:Web.Debug.Config,Web.Release.Config,Web.Staging Config.

4个设置代理

通过在解决方案资源管理器中单击项目,然后选择添加",将批处理文件添加到每个代理项目中.新项目".使用文本文件并将其命名为"CreateProxy.bat".

将以下内容插入新文件并保存:

  :: ============================================================================================::从服务wsdl创建代理文件::输入参数:: SDK路径svcutil.exe的位置:: WSDL文件Arg1(%1)::输出代理.CS文件Arg2(%2)::::由BeforeBuild目标的构建过程调用,以重新生成代理代码.::确保更改FooService.proxy:: ==========================================================================================svcutil%1/ct:System.Collections.Generic.List`1/serializer:DataContractSerializer/tcv:Version35/n:*,FooService.Proxy/out:%2 

现在,右键单击代理项目,然后单击卸载项目",如果出现提示,则进行保存.这将使我们能够进入和修改项目文件.右键单击现在变灰的代理项目名称,然后选择编辑".

在结束的</project> 标记之前添加以下内容.请注意,您可能需要更改路径 SDKPath ,具体取决于您 svcutil 的位置.还要确保将 FooService_proxy.cs 命名为您命名代理文件的任何名称.

 < PropertyGroup><!-这些属性由BeforeBuild Target中的svcutil批处理文件任务使用,以重新生成代理代码->< SDKPath条件='$(SDKPath)'==''''> C:\ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ bin</SDKPath>< WSDLPath Condition ='$(WSDLPath)'=="和'$(Configuration)'=='Debug''> http://[测试服务器服务的路径]</WSDLPath>< WSDLPath Condition ='$(WSDLPath)'=="和'$(Configuration)'=='Staging''> http://[STAGING服务器服务的路径]</WSDLPath>< WSDLPath Condition ='$(WSDLPath)'=="和'$(Configuration)'=='Release''> http://[LIVE Server Service的路径]</WSDLPath>< SkipProxyRegen Condition =''$(SkipProxyRegen)'=='''> false</SkipProxyRegen></PropertyGroup><目标名称="BeforeBuild"><消息重要性=正常";Text =从批处理文件'$(ProjectDir)CreateProxy.bat中重建代理代码".条件='$(SkipProxyRegen)'=='假'''/>< Exec Command ="$(ProjectDir)CreateProxy.bat $(WSDLPath)$(ProjectDir)FooService_proxy.cs"WorkingDirectory ="$(SDKPath)";条件='$(SkipProxyRegen)'=='假'''/></Target> 

保存更改,然后右键单击显示为灰色的项目名称,然后选择重新加载项目".

右键单击该项目,然后选择"build",确保现在已填充您的代理文件.

设置每个代理项目,以使其始终仅建立在其' \ bin 目录中,例如不是 bin \ debug 等.右键单击代理项目,然后选择属性".选择构建"标签并更改配置"下拉至所有配置".设置输出路径"为到 bin \

5将代理参考和端点添加到您的网站

通过右键单击参考",将对每个代理项目的引用添加到您的Webstie中.添加引用"然后转到项目"标签.

现在打开您的web.config文件并添加绑定,并使用以前的web.config作为指南.

 < system.serviceModel>< bindings>< basicHttpBinding>< binding name =" fooServiceEndpoint" ;;closeTimeout ="00:01:00";openTimeout ="00:01:00"receiveTimeout ="00:10:00"sendTimeout ="00:01:00";allowCookies ="false"BypassProxyOnLocal ="false";hostNameComparisonMode ="StrongWildcard"maxBufferSize ="2147483647";maxBufferPoolSize ="524288"maxReceivedMessageSize ="2147483647";messageEncoding =文本"textEncoding ="utf-8";transferMode =缓冲的".useDefaultWebProxy ="true"< readerQuotas maxDepth ="32"maxStringContentLength ="2147483647";maxArrayLength ="2147483647";maxBytesPerRead ="8192".maxNameTableCharCount ="2147483647";/><安全模式=无">< transport clientCredentialType ="None"proxyCredentialType =无".realm ="/>< message clientCredentialType =" UserName"algorithmSuite =默认"/></security></binding><!-根据需要插入其他绑定-></basicHttpBinding></bindings><客户><!-测试服务器端点-用于日常开发-><端点地址="http:[测试服务器服务的路径]"binding ="basicHttpBinding"bindingConfiguration ="fooServiceEndpoint";contract ="FooService.Proxy.IFooService"name =" fooServiceEndpoint"/><!-根据需要添加其他端点-><!-登台服务器端点-偶尔使用<端点地址="http:[STAGING Server服务的路径]"binding ="basicHttpBinding"bindingConfiguration ="fooServiceEndpoint";contract ="FooService.Proxy.IFooService"name =" fooServiceEndpoint"/><这里也有其他终点/>-><!-LIVEServer端点-很少使用,并且要小心<端点地址="http:[到LIVE Server服务的路径]"binding ="basicHttpBinding"bindingConfiguration ="fooServiceEndpoint";contract ="FooService.Proxy.IFooService"name =" fooServiceEndpoint"/><这里也有其他终点/>-></client></system.serviceModel> 

现在,您可以简单地用注释修改Web配置,这取决于要在哪个服务器上进行调试

6设置web.config转换以进行部署

在解决方案资源管理器中展开web.config节点.

打开 web.staging.config 文件并添加以下内容:

 < system.serviceModel><客户><端点地址="http:[STAGING服务器服务的路径]"binding ="basicHttpBinding"bindingConfiguration ="fooServiceEndpoint";contract ="FooService.Proxy.IFooService"name =" fooServiceEndpoint"xdt:Transform =" SetAttributes"xdt:Locator ="Match(name)"./></client><!-重复其他端点-></system.serviceModel> 

现在将相同的内容添加到 Web.Release.Config 中,以将路径更改为LIVE服务器路径.现在,使用VisualStudio发布命令发布时,将使用适当的端点.

例如如果部署网站的STAGING版本,则选择暂存".从构建配置"下拉列表中.右键单击解决方案展开器中的WebSite项目,然后选择发布".选择您希望的发布方式,然后点击发布"按钮.然后将重新构建整个解决方案,从登台服务器生成代理,并使用登台设置发布web.config文件.

就这样,您完成了

您现在将具有基于您的构建配置生成的代理,一个位置,该位置可通过注释来更改路径以进行调试,并在发布时自动进行web.config更新.

更新

OP的盖伊(Gaui)创建了一个小exe,可简化此操作.它在 GitHub

上可用

I have a C# ASP.NET project with 15 WCF/ASMX Service References. Each service is deployed to three different servers; test, staging and live.

Often we need to change the URLs of these service references to different servers, to be able to debug using the correct service with the correct implementation and data.

When managing these Service References I'm having a hard time keeping the URL in sync. When creating a Service Reference FooService it stores the URL in three seperate files:

  • FooService.disco
  • configuration.svcinfo
  • Reference.svcmap

Along with creating an endpoint node with the URL in the Web.config.

If I change the endpoint URL in the Web.config and rebuild the project, it doesn't update the URL in the other files, so it's out of sync. So when I right-click the FooService and click Update Service Reference it doesn't use the URL stored in the Web.config, it uses the URL in the other files.

So the only way is to right-click the FooService and click on Configure Service Reference and enter the new URL. But that doesn't always work, because sometimes it creates a new node in Web.config named FooService1, so I get an error when running my application saying that there are two instances of the same endpoints.

So often I need to skim through the Web.config and delete duplicates of endpoints, which is very frustrating.

What is the best way to manage multiple WCF service references when changing the URL to the service often?

解决方案

First an overview

The way I handle it is to not add the service refernce via Visual Studio. What I have is each service has it's own Proxy project in the solution, to proxy is created using a simple one line batch file. Each of these is then included in the website(s) as a "vanilla" reference. The end point is configured maunally in the web config. I have three deployment options: Debug (local), Staging and Release. At the web.config level the differnt addresses are handled by web.config transformations . The proxy project files are configured so that the correct end point address is used depending on the solution configuration. However it is important to note that web.config transofrmations only apply on publishing the solution.

In pre VS2010 I had 3 variations of the web.config files which would overite the active web.config; however overwriting the web.config in this way always felt "risky" to me. In this case I think that using transforms for publish will still work, but in the actual web.config file have block of connections that you can comment in and out on those occations when you want to debug the staging or development servers.

I only have 2 services, so my set up was pretty easy, with 15 there will be a fair bit of work involved to set up, but it will save you head aches in the long run.

Implementation

Back Up Everything First!!

Also keep handy a copy of the existing web.config to help with configuring the end points later on.

Also note that the batch files won't work if your solution is in a path with a space in its name, e.g. the default location VS puts its' projects. All my projects are in the following structure C:\Source\vs2008\, C:\Source\vs2010\ etc. I'll see if I can find a better solution for this.

0 Run VisualStudio as an administrator

Right click Visual Studio from the start menu and select "Run as Administrator". We need to do this as VS will be writing files.

1 Delete Exising service references

You shouldn't need any help on this one.

2 Add Proxy Projects

Doing this now means you only need configure the solution for test|staging|live once.

From the File menu select "Add" then "New Project" and from unser the "Visual C#" tmplates select "Class Library" and name it something sensible. I'll be using FooService.proxy for this example. Rename the class file, I'll be using FooService_proxy.cs in this example.

Add the following references to the project:

  • System.Runtime.Serialization
  • System.ServiceModel

Add one project for each service. We will comeback and update these projects later.

3 Configure The Solution to handle test|staging|live

I'm assuming you use test when developing the asp.net website on your local machine.

Open the "Configuration Manager" by selecting it in the Build Configuration dropdown menu.

Under the "Active Solution Configuration" dropdown select "New"

For the Name I'd suggest "Staging" and check the "Create new project confogurations" check box.

In the Solution Explorer, right click on Web.Config and select "Add config transforms". This will add a new file for the staging web.config transformation. Click the expander arrow and you will see three sub files: Web.Debug.Config, Web.Release.Config, Web.Staging Config.

4 Set Up Proxies

Add a batch file to each proxy project by Clicking on the project in the solution explorer and selecting "Add > New Item". Use a text file and name it "CreateProxy.bat.

Insert the following into the new file and save:

:: ============================================================================================
:: Create the proxy file from the service wsdl
:: Input parameters
:: SDK Path The location of svcutil.exe
:: WSDL File Arg1 (%1)
:: Output Proxy .CS file Arg2 (%2)
::
:: Called by the build process of the BeforeBuild target to re-gen the proxy code.
:: Make sure to change FooService.proxy
:: ============================================================================================

svcutil %1 /ct:System.Collections.Generic.List`1 /serializer:DataContractSerializer  /tcv:Version35  /n:*,FooService.Proxy /out:%2

Now right click on the proxy project and click "Unload Project", saving if prompted. This will enable us to get in and modify the project file. Right Click the now greyed out proxy project name and select "Edit".

Add the following just befor the closing </project> tag. Note you may need to change the path SDKPath depending on your location of svcutil. Also make sure to name FooService_proxy.cs whatever you named the proxy file.

<PropertyGroup>
  <!-- These properties are used by the svcutil batch file task in the BeforeBuild Target to regen the proxy code -->

  <SDKPath Condition="'$(SDKPath)'==''">C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin</SDKPath>
  <WSDLPath Condition="'$(WSDLPath)'=='' and '$(Configuration)' == 'Debug'">http://[Path to TEST Server Service]</WSDLPath>
  <WSDLPath Condition="'$(WSDLPath)'=='' and '$(Configuration)' == 'Staging'">http://[Path to STAGING server Service]</WSDLPath>
  <WSDLPath Condition="'$(WSDLPath)'=='' and '$(Configuration)' == 'Release'">http://[Path to LIVE Server Service]</WSDLPath>
  <SkipProxyRegen Condition="'$(SkipProxyRegen)'==''">false</SkipProxyRegen>
</PropertyGroup>
<Target Name="BeforeBuild">
  <Message Importance="normal" Text="Rebuilding the proxy code from batch file '$(ProjectDir)CreateProxy.bat'" Condition="'$(SkipProxyRegen)'=='false'" />
  <Exec Command="$(ProjectDir)CreateProxy.bat $(WSDLPath) $(ProjectDir)FooService_proxy.cs" WorkingDirectory="$(SDKPath)" Condition="'$(SkipProxyRegen)'=='false'" />
</Target>

Save the changes and then right click on the greyed out project name and select "Reload Project".

Right click on the project and select build, make sure that your proxy file is now populated.

Set each proxy project so that it always build into only its' \bin directory, e.g. not bin\debug etc. Right click on the proxy project and select "Properties". Select the "Build" tab and change the "Configuration" drop down to "All Configurations". Set the "Output path" to bin\

5 Add Proxy References and End Points To Your Website

Add a reference to each proxy project to your webstie by right clicking "References > Add reference" and then going to the "Projects" Tab.

Now open up your web.config file and add the bindings, use your previous web.config as a guide.

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="fooServiceEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
                bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
                    maxBytesPerRead="8192" maxNameTableCharCount="2147483647" />
                <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default" />
                </security>
            </binding>
            <!-- Insert other binding as required -->
        </basicHttpBinding>
    </bindings>
    <client>
        <!-- Test Server Endpoints - Used for day-to-day development -->
        <endpoint address="http:[Path to TEST Server service]"
        binding="basicHttpBinding" bindingConfiguration="fooServiceEndpoint"
        contract="FooService.Proxy.IFooService" name="fooServiceEndpoint" />
        <!-- Add Other endpoints as required -->

        <!-- Staging Server End Points - Used Occasionaly
        <endpoint address="http:[Path to STAGING Server service]"
        binding="basicHttpBinding" bindingConfiguration="fooServiceEndpoint"
        contract="FooService.Proxy.IFooService" name="fooServiceEndpoint" />
        <other end points here too />
        -->

        <!-- LIVEServer End Points - Used Rarely and with CAUTION
        <endpoint address="http:[Path to LIVE Server service]"
        binding="basicHttpBinding" bindingConfiguration="fooServiceEndpoint"
        contract="FooService.Proxy.IFooService" name="fooServiceEndpoint" />
        <other end points here too />
        -->
    </client>
</system.serviceModel>

Now you can simply modify the web config with comments depending on which server you want to be debuging on

6 Set up web.config transformation for deployment

Expand the web.config node in the solution explorer.

Open the web.staging.config file and add the following:

<system.serviceModel>
    <client>
        <endpoint address="http:[Path to STAGING server Service]"
        binding="basicHttpBinding" bindingConfiguration="fooServiceEndpoint"
        contract="FooService.Proxy.IFooService" name="fooServiceEndpoint" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
    </client>
    <!-- Repeat for additional end points -->
</system.serviceModel>

Now add the same to Web.Release.Config changing the paths to tho the LIVE server paths. This will now use the appropriate endpoints when published using the VisualStudio publish command.

E.g. If deploying a STAGING version of the web site, select "Staging" from the Build Configuraion drop down. Right click on the WebSite project in the solution expolorer and select "Publish". Choose how you wish to publish and click the "Publish" button. The whole solution will then rebuild, proxies will be generated form the Staging server and the web.config file will be published with the Staging setting.

Thats it, you're done

You now have proxies that will generate based on your build configuration, one location to change paths via commenting for debugging purposes, and automatic web.config updating on publising.

Update

Gaui, the OP, has created a small exe that simplifies this some what. It is availavle on GitHub

这篇关于在.NET中管理多个服务引用的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆