【问题标题】:How to get rid of app.config and move it all into code?如何摆脱 app.config 并将其全部移动到代码中?
【发布时间】:2013-09-25 03:34:11
【问题描述】:

我在这篇文章中以通用方式尝试了这个问题:https://stackoverflow.com/q/18968846/147637

但这并没有让我们得到结果。

Soooo,具体到这里!

我有下面的代码。有用。在 VS 中,您添加一个 Web 引用,在下面编写代码,然后....开始摆弄 app.config。

而且它有效。

但我需要摆脱应用配置。代码的关键部分不在....代码中是一个问题。很难记录,而且查看此示例的人们很容易忘记查看应用配置(这是其他开发人员的示例)。

所以问题是:如何将 app.config 的内容移动到代码中?

(我是一名兼职编码员。向我指出通用文档不会让我到达那里,抱歉!)

**// .cs file:**

using myNameSpace.joesWebService.WebAPI.SOAP;

namespace myNameSpace
{
    class Program
    {
        static void Main(string[] args)
        {
            // create the SOAP client
            joesWebServerClient server = new joesWebServerClient();

            string payloadXML = Loadpayload(filename);

            // Run the SOAP transaction
            string response = server.WebProcessShipment(string.Format("{0}@{1}", Username, Password), payloadXML);

=================================================
**app.config**

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <!--  Some non default stuff has been added by hand here    -->
                <binding name="IjoesWebServerbinding" maxBufferSize="256000000" maxReceivedMessageSize="256000000" />
            </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://joesWebServer/soap/IEntryPoint"
                    binding="basicHttpBinding" bindingConfiguration="IjoesWebServerbinding"
                    contract="myNameSpace.joesWebService.WebAPI.SOAP.IjoesWebServer"
                    name="IjoesWebServerSOAP" />
        </client>
      </system.serviceModel>
</configuration>

【问题讨论】:

  • @Hi-TechKitKatAndroid 你刚刚博加特我的编辑了吗?!?!
  • @paqogomez 如果您删除了 .Net 4.5,那么您应该将该特定标签添加到问题中,否则不要删除
  • @Hi-TechKitKatAndroid,我很抱歉,我没有意识到它还没有被添加。
  • @paqogomez 没关系记得下次

标签: c# .net wcf .net-4.5


【解决方案1】:

一般来说,配置文件比硬编码设置更受欢迎,因为您需要对配置文件做的就是更改要更改的值,然后重新启动应用程序。如果它们是硬编码的,则必须修改源代码、重新编译和重新部署。

话虽如此,您几乎可以在代码中完成在 WCF 配置文件中所做的所有事情(我似乎记得一些例外情况,但暂时不记得了)。

实现您所寻找的一种方法是在您的代码中定义绑定并通过ChannelFactory&lt;T&gt; 创建客户端,其中T 是您的服务的接口(更准确地说是服务合同,通常是在接口中,然后由类实现)。

例如:

using System.ServiceModel;
using myNameSpace.joesWebService.WebAPI.SOAP;

namespace myNameSpace
{
    class Program
    {
        static void Main(string[] args)
        {

        // Create the binding
        BasicHttpBinding myBinding = new BasicHttpBinding();
        myBinding.MaxBufferSize = 256000000;
        myBinding.MaxReceivedMessageSize = 256000000;

        // Create the Channel Factory
        ChannelFactory<IjoesWebServer> factory =
            new ChannelFactory<IjoesWebServer>(myBinding, "http://joesWebServer/soap/IEntryPoint");

        // Create, use and close the client
        IjoesWebService client = null;
        string payloadXML = Loadpayload(filename);
        string response;

        try
        {
            client = factory.CreateChannel();
            ((IClientChannel)client).Open();

            response = client.WebProcessShipment(string.Format("{0}@{1}", Username, Password), payloadXML);

            ((IClientChannel)client).Close();
        }
        catch (Exception ex)
        {
            ((ICientChannel)client).Abort();

            // Do something with the error (ex.Message) here
        }
    }
}

现在您不需要配置文件。您在示例中的附加设置现在在代码中。

ChannelFactory&lt;T&gt; 的优势在于,一旦创建了工厂实例,就可以通过调用CreateChannel() 随意生成新通道(将它们视为客户端)。这将加快速度,因为您的大部分开销都将用于创建工厂。

附加说明 - 您在配置文件的很多地方都使用了I&lt;name&gt;。 I 通常表示一个接口,如果一个全职开发人员要查看您的项目,乍一看可能会让他们有些困惑。

【讨论】:

  • 蒂姆,谢谢!我几乎所有的工作。一行不起作用:client = ((ICommunicationObject)facto... 这会抛出“无法将类型 'void' 隐式转换为 'myNameSpace.joesWebService.WebAPI.SOAP.joesWebServerClient”
  • @Jonesome - 对不起;这是我昨晚凭记忆写的。我已将示例修改为使用IClientChannel 而不是ICommunicationObject,并将创建通道和打开行分成两行。
【解决方案2】:

在 WCF 4.5 中,如果您向 WCF 服务类添加静态配置方法,那么它将自动加载并忽略 app.config 文件中的内容。

<ServiceContract()>
Public Interface IWCFService

    <OperationContract()>
    Function GetData(ByVal value As Integer) As String

    <OperationContract()>
    Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType

End Interface

Public Class WCFService
    Implements IWCFService

    Public Shared Function CreateClient() As Object

    End Function
    Public Shared Sub Configure(config As ServiceConfiguration)
        'Define service endpoint
        config.AddServiceEndpoint(GetType(IWCFService), _
                                  New NetNamedPipeBinding, _
                                  New Uri("net.pipe://localhost/WCFService"))

        'Define service behaviors
        Dim myServiceBehaviors As New Description.ServiceDebugBehavior With {.IncludeExceptionDetailInFaults = True}
        config.Description.Behaviors.Add(myServiceBehaviors)

    End Sub

    Public Function GetData(ByVal value As Integer) As String Implements IWCFService.GetData
        Return String.Format("You entered: {0}", value)
    End Function

    Public Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType Implements IWCFService.GetDataUsingDataContract

    End Function

End Class

我仍在研究如何为客户做同样的事情。如果有兴趣,我会在弄清楚时尝试更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多