문제

구성 파일을 사용하지 않고 프로그래밍 방식으로 WCF 서비스를 노출하는 방법에 대한 좋은 예를 아는 사람이 있습니까?이제 WCF를 사용하면 서비스 개체 모델이 훨씬 더 풍부해지기 때문에 이것이 가능하다는 것을 알고 있습니다.나는 그렇게 하는 방법에 대한 예를 본 적이 없습니다.반대로 구성 파일 없이 소비하는 방법도 확인하고 싶습니다.

누군가 묻기 전에 구성 파일 없이 이 작업을 수행해야 한다는 매우 구체적인 요구 사항이 있습니다.나는 일반적으로 그러한 관행을 권장하지 않지만 앞서 말했듯이 이 경우에는 매우 특별한 필요성이 있습니다.

도움이 되었습니까?

해결책

내가 발견한 것처럼 구성 파일 없이 웹 서비스를 사용하는 것은 매우 간단합니다.바인딩 객체와 주소 객체를 생성하고 이를 클라이언트 프록시의 생성자 또는 일반 ChannelFactory 인스턴스에 전달하기만 하면 됩니다.기본 app.config를 보고 어떤 설정을 사용할지 확인한 다음 프록시를 인스턴스화하는 정적 도우미 메서드를 만들 수 있습니다.

internal static MyServiceSoapClient CreateWebServiceInstance() {
    BasicHttpBinding binding = new BasicHttpBinding();
    // I think most (or all) of these are defaults--I just copied them from app.config:
    binding.SendTimeout = TimeSpan.FromMinutes( 1 );
    binding.OpenTimeout = TimeSpan.FromMinutes( 1 );
    binding.CloseTimeout = TimeSpan.FromMinutes( 1 );
    binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 );
    binding.AllowCookies = false;
    binding.BypassProxyOnLocal = false;
    binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
    binding.MessageEncoding = WSMessageEncoding.Text;
    binding.TextEncoding = System.Text.Encoding.UTF8;
    binding.TransferMode = TransferMode.Buffered;
    binding.UseDefaultWebProxy = true;
    return new MyServiceSoapClient( binding, new EndpointAddress( "http://www.mysite.com/MyService.asmx" ) );
}

다른 팁

IIS 호스팅용 web.config에서 System.ServiceModel 섹션의 사용을 제거하는 데 관심이 있다면 여기에 그 방법에 대한 예를 게시했습니다(http://bejabbers2.blogspot.com/2010/02/wcf-zero-config-in-net-35-part-ii.html).메타데이터와 wshttpbind 엔드포인트를 모두 생성하기 위해 ServiceHost를 사용자 지정하는 방법을 보여줍니다.추가 코딩이 필요하지 않은 일반적인 목적의 방식으로 수행합니다..NET 4.0으로 즉시 업그레이드하지 않는 사람들에게는 이것이 매우 편리할 수 있습니다.

여기, 이것은 완전하고 작동하는 코드입니다.나는 그것이 당신에게 많은 도움이 될 것이라고 생각합니다.검색 중 완전한 코드를 찾지 못했기 때문에 완전하고 작동하는 코드를 넣으려고 했습니다.행운을 빌어요.

public class ValidatorClass
{
    WSHttpBinding BindingConfig;
    EndpointIdentity DNSIdentity;
    Uri URI;
    ContractDescription ConfDescription;

    public ValidatorClass()
    {  
        // In constructor initializing configuration elements by code
        BindingConfig = ValidatorClass.ConfigBinding();
        DNSIdentity = ValidatorClass.ConfigEndPoint();
        URI = ValidatorClass.ConfigURI();
        ConfDescription = ValidatorClass.ConfigContractDescription();
    }


    public void MainOperation()
    {
         var Address = new EndpointAddress(URI, DNSIdentity);
         var Client = new EvalServiceClient(BindingConfig, Address);
         Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
         Client.Endpoint.Contract = ConfDescription;
         Client.ClientCredentials.UserName.UserName = "companyUserName";
         Client.ClientCredentials.UserName.Password = "companyPassword";
         Client.Open();

         string CatchData = Client.CallServiceMethod();

         Client.Close();
    }



    public static WSHttpBinding ConfigBinding()
    {
        // ----- Programmatic definition of the SomeService Binding -----
        var wsHttpBinding = new WSHttpBinding();

        wsHttpBinding.Name = "BindingName";
        wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
        wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.BypassProxyOnLocal = false;
        wsHttpBinding.TransactionFlow = false;
        wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
        wsHttpBinding.MaxBufferPoolSize = 524288;
        wsHttpBinding.MaxReceivedMessageSize = 65536;
        wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;
        wsHttpBinding.TextEncoding = Encoding.UTF8;
        wsHttpBinding.UseDefaultWebProxy = true;
        wsHttpBinding.AllowCookies = false;

        wsHttpBinding.ReaderQuotas.MaxDepth = 32;
        wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;
        wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;
        wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
        wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;

        wsHttpBinding.ReliableSession.Ordered = true;
        wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
        wsHttpBinding.ReliableSession.Enabled = false;

        wsHttpBinding.Security.Mode = SecurityMode.Message;
        wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
        wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
        wsHttpBinding.Security.Transport.Realm = "";

        wsHttpBinding.Security.Message.NegotiateServiceCredential = true;
        wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
        // ----------- End Programmatic definition of the SomeServiceServiceBinding --------------

        return wsHttpBinding;

    }

    public static Uri ConfigURI()
    {
        // ----- Programmatic definition of the Service URI configuration -----
        Uri URI = new Uri("http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/");

        return URI;
    }

    public static EndpointIdentity ConfigEndPoint()
    {
        // ----- Programmatic definition of the Service EndPointIdentitiy configuration -----
        EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity("tempCert");

        return DNSIdentity;
    }


    public static ContractDescription ConfigContractDescription()
    {
        // ----- Programmatic definition of the Service ContractDescription Binding -----
        ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService), typeof(EvalServiceClient));

        return Contract;
    }
}

서버에선 쉽지 않네요 ..

클라이언트 측에서는 다음을 사용할 수 있습니다. 채널팩토리

모든 WCF 구성은 프로그래밍 방식으로 수행할 수 있습니다.따라서 구성 파일 없이 서버와 클라이언트를 모두 만드는 것이 가능합니다.

프로그래밍 방식 구성의 많은 예가 포함된 Juval Lowy의 "Programming WCF Services" 책을 추천합니다.

클라이언트 측과 서버 측 모두에서 수행하는 것은 매우 쉽습니다.Juval Lowy의 책에는 훌륭한 예가 나와 있습니다.

구성 파일에 대한 귀하의 의견에 관해서는 구성 파일이 코드에서 수행하는 가난한 사람의 두 번째라고 말하고 싶습니다.구성 파일은 서버에 연결되는 모든 클라이언트를 제어하고 업데이트되었는지 확인하고 사용자가 해당 파일을 찾아 아무것도 변경할 수 없도록 할 때 유용합니다.WCF 구성 파일 모델은 제한적이고 디자인하기가 다소 어렵고 유지 관리가 악몽이라고 생각합니다.전체적으로 MS가 구성 파일을 기본 작업 방식으로 만드는 것은 매우 잘못된 결정이라고 생각합니다.

편집하다:구성 파일로 수행할 수 없는 작업 중 하나는 기본이 아닌 생성자를 사용하여 서비스를 만드는 것입니다.이로 인해 WCF에서는 정적/전역 변수, 싱글톤 및 기타 의미 없는 유형이 발생합니다.

이 주제와 관련된 아래 링크의 블로그 게시물이 매우 흥미로웠습니다.

제가 좋아하는 한 가지 아이디어는 바인딩이나 동작 또는 주소 XML 섹션을 구성에서 적절한 WCF 개체로 전달하고 속성 할당을 처리하도록 할 수 있다는 것입니다. 현재로서는 이 작업을 수행할 수 없습니다.

웹상의 다른 사람들과 마찬가지로 호스팅 응용 프로그램(.NET 2.0 Windows 서비스)의 구성 파일과 다른 구성 파일을 사용하려면 WCF 구현이 필요한 문제가 있습니다.

http://salvoz.com/blog/2007/12/09/programmatically-setting-wcf-configuration/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top