다음을 통해 공유


방법: 관리되는 응용 프로그램에서 WCF 서비스 호스팅

관리되는 응용 프로그램 내에서 서비스를 호스팅하려면 관리되는 응용 프로그램 코드 내에 서비스에 대한 코드를 포함하고, 코드에서 명령적으로, 구성을 통해 선언적으로 또는 기본 끝점을 사용해 서비스에 대한 끝점을 정의한 다음 ServiceHost의 인스턴스를 만듭니다.

메시지 받기를 시작하려면 ServiceHost에서 Open을 호출합니다. 이렇게 하면 서비스에 대한 수신기가 만들어지고 열립니다. 관리되는 응용 프로그램이 호스팅 작업을 직접 수행하므로 이런 방식으로 서비스를 호스팅하는 것을 "자체 호스팅"이라고 합니다. 서비스를 닫으려면 ServiceHost에서 System.ServiceModel.Channels.CommunicationObject.Close를 호출합니다.

서비스는 관리되는 Windows 서비스, IIS(인터넷 정보 서비스) 또는 WAS(Windows Process Activation Service)에서 호스팅될 수도 있습니다. 서비스 호스팅 옵션에 대한 자세한 내용은 서비스 호스팅을 참조하십시오.

관리되는 응용 프로그램에서의 서비스 호스팅은 배포하는 데 최소한의 인프라를 필요로 하므로 가장 유연한 옵션입니다. 관리되는 응용 프로그램에서의 서비스 호스팅에 대한 자세한 내용은 관리되는 응용 프로그램에서의 호스팅을 참조하십시오.

다음 절차에서는 콘솔 응용 프로그램에서 자체 호스팅된 서비스를 구현하는 방법을 보여 줍니다.

자체 호스팅된 서비스를 만들려면

  1. Visual Studio 2010을 열고 파일 메뉴에서 새로 만들기를 선택한 다음 **프로젝트…**를 선택합니다.

  2. 설치된 템플릿 목록에서 Visual C#, Windows 또는 Visual Basic, Windows를 선택합니다. Visual Studio 2010 설정에 따라 이들 옵션 중 하나 또는 둘 모두 설치된 템플릿 목록의 다른 언어 노드 아래에 있을 수 있습니다.

  3. Windows 목록에서 콘솔 응용 프로그램을 선택합니다. 이름 상자에 SelfHost를 입력하고 확인을 클릭합니다.

  4. 솔루션 탐색기에서 SelfHost를 마우스 오른쪽 단추로 클릭하고 **참조 추가…**를 선택합니다. .NET 탭에서 System.ServiceModel을 선택하고 확인을 클릭합니다.

    ms731758.Tip(ko-kr,VS.100).gif팁:
    솔루션 탐색기 창이 표시되어 있지 않으면 보기 메뉴에서 솔루션 탐색기를 선택합니다.

  5. Program.cs 또는 Module1.vb가 아직 열려 있지 않으면 솔루션 탐색기에서 두 번 클릭하여 코드 창에서 엽니다. 파일 맨 위에 다음 문을 추가합니다.

    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
  6. 서비스 계약을 정의 및 구현합니다. 이 예제에서는 서비스에 대한 입력을 기준으로 메시지를 반환하는 HelloWorldService를 정의합니다.

    <ServiceContract()>
    Public Interface IHelloWorldService
        <OperationContract()>
        Function SayHello(ByVal name As String) As String
    End Interface
    
    Public Class HelloWorldService
        Implements IHelloWorldService
    
        Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
            Return String.Format("Hello, {0}", name)
        End Function
    End Class
    
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }
    
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }
    
    ms731758.note(ko-kr,VS.100).gif참고:
    서비스 인터페이스를 정의 및 구현하는 방법에 대한 자세한 내용은 방법: Windows Communication Foundation 서비스 계약 정의방법: Windows Communication Foundation 서비스 계약 구현을 참조하십시오.

  7. 서비스의 기본 주소를 사용하여 Main 메서드 맨 위에 Uri 클래스의 인스턴스를 만듭니다.

    Dim baseAddress As Uri = New Uri("https://localhost:8080/hello")
    
    Uri baseAddress = new Uri("https://localhost:8080/hello");
    
  8. ServiceHost 클래스의 인스턴스를 만들어 서비스 형식 및 기본 주소 URI(Uniform Resource Identifier)를 나타내는 Type을 ServiceHost에 전달합니다. 메타데이터 게시를 사용하도록 설정한 다음 ServiceHost에서 Open 메서드를 호출하여 서비스를 초기화하고 메시지를 받도록 서비스를 준비합니다.

    ' Create the ServiceHost.
    Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)
    
        ' Enable metadata publishing.
        Dim smb As New ServiceMetadataBehavior()
        smb.HttpGetEnabled = True
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
        host.Description.Behaviors.Add(smb)
    
        ' Open the ServiceHost to start listening for messages. Since
        ' no endpoints are explicitly configured, the runtime will create
        ' one endpoint per base address for each service contract implemented
        ' by the service.
        host.Open()
    
        Console.WriteLine("The service is ready at {0}", baseAddress)
        Console.WriteLine("Press <Enter> to stop the service.")
        Console.ReadLine()
    
        ' Close the ServiceHost.
        host.Close()
    
    End Using
    
    // Create the ServiceHost.
    using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
    {
        // Enable metadata publishing.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
        host.Description.Behaviors.Add(smb);
    
        // Open the ServiceHost to start listening for messages. Since
        // no endpoints are explicitly configured, the runtime will create
        // one endpoint per base address for each service contract implemented
        // by the service.
        host.Open();
    
        Console.WriteLine("The service is ready at {0}", baseAddress);
        Console.WriteLine("Press <Enter> to stop the service.");
        Console.ReadLine();
    
        // Close the ServiceHost.
        host.Close();
    }
    
    ms731758.note(ko-kr,VS.100).gif참고:
    이 예제에서는 기본 끝점을 사용하며, 이 서비스에는 구성 파일이 필요하지 않습니다. 끝점을 구성하지 않으면 런타임이 서비스에서 구현되는 각 서비스 계약의 각 기본 주소에 대해 끝점을 하나씩 만듭니다. 기본 끝점에 대한 자세한 내용은 단순화된 구성Simplified Configuration for WCF Services을 참조하십시오.

  9. Ctrl+Shift+B를 눌러 솔루션을 빌드합니다.

서비스를 테스트하려면

  1. 서비스를 실행하려면 Ctrl+F5를 누릅니다.

  2. WCF 테스트 클라이언트를 엽니다.

    ms731758.Tip(ko-kr,VS.100).gif팁:
    WCF 테스트 클라이언트를 열려면 Visual Studio 2010 명령 프롬프트를 열고 WcfTestClient.exe를 실행합니다.

  3. 파일 메뉴에서 **서비스 추가...**를 선택합니다.

  4. 주소 상자에 https://localhost:8080/hello를 입력하고 확인을 클릭합니다.

    ms731758.Tip(ko-kr,VS.100).gif팁:
    서비스가 실행 중인지 확인하십시오. 그렇지 않으면 이 단계는 실패합니다. 코드에서 기본 주소를 변경한 경우에는 이 단계에서 수정된 기본 주소를 사용하십시오.

  5. 내 서비스 프로젝트 노드 아래의 SayHello를 두 번 클릭하고 요청 목록의 열에 사용자 이름을 입력한 다음 호출을 클릭합니다. 그러면 응답 목록에 회신 메시지가 나타납니다.

예제

다음 예제에서는 ServiceHost 개체를 만들어 HelloWorldService 형식의 서비스를 호스팅한 다음 ServiceHost에서 Open 메서드를 호출합니다. 기본 주소는 코드에서 제공되고 메타데이터 게시가 사용하도록 설정되며 기본 끝점이 사용됩니다.

Imports System.ServiceModel
Imports System.ServiceModel.Description

Module Module1

    <ServiceContract()>
    Public Interface IHelloWorldService
        <OperationContract()>
        Function SayHello(ByVal name As String) As String
    End Interface
    
    Public Class HelloWorldService
        Implements IHelloWorldService

        Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
            Return String.Format("Hello, {0}", name)
        End Function
    End Class

    Sub Main()
        Dim baseAddress As Uri = New Uri("https://localhost:8080/hello")

        ' Create the ServiceHost.
        Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)

            ' Enable metadata publishing.
            Dim smb As New ServiceMetadataBehavior()
            smb.HttpGetEnabled = True
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
            host.Description.Behaviors.Add(smb)

            ' Open the ServiceHost to start listening for messages. Since
            ' no endpoints are explicitly configured, the runtime will create
            ' one endpoint per base address for each service contract implemented
            ' by the service.
            host.Open()

            Console.WriteLine("The service is ready at {0}", baseAddress)
            Console.WriteLine("Press <Enter> to stop the service.")
            Console.ReadLine()

            ' Close the ServiceHost.
            host.Close()

        End Using

    End Sub

End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace SelfHost
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }

    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("https://localhost:8080/hello");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}

참고 항목

작업

방법: IIS에서의 WCF 서비스 호스팅
Self-Host
방법: Windows Communication Foundation 서비스 계약 정의
방법: Windows Communication Foundation 서비스 계약 구현

참조

Uri
AppSettings
ConfigurationManager

개념

서비스 호스팅
ServiceModel Metadata 유틸리티 도구(Svcutil.exe)
바인딩을 사용하여 서비스 및 클라이언트 구성
시스템 제공 바인딩