C# 如何摆脱app.config并将其全部转换为代码?

C# 如何摆脱app.config并将其全部转换为代码?,c#,.net,wcf,.net-4.5,C#,.net,Wcf,.net 4.5,我在这篇文章中以一种通用的方式尝试了这个问题: 但这并没有让我们得到结果 太好了,这里是具体的 我有下面的代码。它起作用了。在VS中,您添加一个web引用,在下面编写代码,然后。。。。开始摆弄app.config 它是有效的 但我需要去掉应用程序配置。这是一个问题,关键的代码片段不在。。。。密码这是很难记录的,而且看这个例子的人很容易忘记查看应用程序配置。这是其他开发人员的一个例子 所以问题是:如何将app.config的内容移动到代码中 我是一名兼职编码员。抱歉地说,将我指向通用文档并不能使我

我在这篇文章中以一种通用的方式尝试了这个问题:

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

太好了,这里是具体的

我有下面的代码。它起作用了。在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>

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

话虽如此,您几乎可以在代码中完成WCF配置文件中所做的一切。我似乎记得一些例外情况,但不要马上记住它们

实现所需功能的一种方法是在代码中定义绑定并通过ChannelFactory创建客户端,其中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的优点是,一旦创建了工厂实例,就可以通过调用CreateChannel随意生成新的通道,将它们视为客户端。这将加快速度,因为您的大部分开销将用于创建工厂


另一个注意事项是,您在配置文件的许多地方都使用了I。我通常指的是一个界面,如果一个全职开发人员查看您的项目,乍一看可能会让他们有点困惑。

一般来说,与硬编码设置相比,配置文件更可取,因为使用配置文件所需做的只是更改要更改的值,然后重新启动应用程序。如果它们是硬编码的,则必须修改源代码、重新编译和重新部署

话虽如此,您几乎可以在代码中完成WCF配置文件中所做的一切。我似乎记得一些例外情况,但不要马上记住它们

实现所需功能的一种方法是在代码中定义绑定并通过ChannelFactory创建客户端,其中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的优点是,一旦创建了工厂实例,就可以通过调用CreateChannel随意生成新的通道,将它们视为客户端。这将加快速度,因为您的大部分开销将用于创建工厂


另一个注意事项是,您在配置文件的许多地方都使用了I。我通常表示一个接口,如果全职开发人员查看您的项目,乍一看可能会让他们有点困惑。

对于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

我还在研究如何为客户做同样的事情。当我确定是否有兴趣时,我会尝试更新。

对于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

我还在研究如何为客户做同样的事情。如果有人感兴趣,我会尝试更新。

@Hi-TechKitKatAndroid你刚才是不是忘了我的编辑@paqogomez如果您删除了.NET4.5,那么您就需要在问题中添加特定的标记,而其他人不会这样做remove@Hi-TechKitKatAndroid,对不起,我还没意识到它还没有被添加。@paqogomez,没关系,记得下一步吗time@Hi-TechKitKatAndroid你刚才把我的编辑搞砸了吗@paqogomez如果您删除了.NET4.5,那么您就需要在问题中添加特定的标记,而其他人不会这样做remove@Hi-TechKitKatAndroid,我很抱歉,我没有意识到它还没有被添加。@paqogomez没关系记得下次Tim,谢谢!我几乎都能用。一行行不通:client=ICommunicationObjectFact。。。此抛出无法将类型“void”隐式转换为“myNameSpace.joesWebService.WebAPI.SOAP”。joesWebServerClient@Jonesome-对不起;我昨晚凭记忆写的。我已经修改了这个例子,使用了IClie
ntChannel取代了ICommunicationObject,并将创建频道和开放行分为两行。Tim,谢谢!我几乎都能用。一行行不通:client=ICommunicationObjectFact。。。此抛出无法将类型“void”隐式转换为“myNameSpace.joesWebService.WebAPI.SOAP”。joesWebServerClient@Jonesome-对不起;我昨晚凭记忆写的。我修改了这个示例,使用IClientChannel代替ICommunicationObject,并将create channel和open行分为两行。