방법: 관리 앱에서 WCF 서비스 호스팅

관리되는 애플리케이션 내에서 서비스를 호스팅하려면 관리되는 애플리케이션 코드 내에 서비스에 대한 코드를 포함하고, 코드에서 명령적으로, 구성을 통해 선언적으로 또는 기본 엔드포인트를 사용해 서비스에 대한 엔드포인트를 정의한 다음 ServiceHost의 인스턴스를 만듭니다.

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

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

관리되는 애플리케이션에서 서비스를 호스팅할 경우 최소한의 배포 인프라를 필요로 하기 때문에 가장 유연한 옵션입니다. 관리되는 애플리케이션에서 서비스를 호스팅하는 방법에 대한 자세한 내용은 관리되는 애플리케이션에서 호스팅을 참조하세요.

다음 절차에서는 콘솔 애플리케이션에서 자체 호스팅된 서비스를 구현하는 방법을 보여 줍니다.

자체 호스팅 서비스 만들기

  1. 새 콘솔 애플리케이션 만들기:

    1. Visual Studio를 열고 파일 메뉴에서 새로 만들기>프로젝트를 선택합니다.

    2. 설치된 템플릿 목록에서 Visual C# 또는 Visual Basic을 선택한 다음 Windows 데스크톱을 선택합니다.

    3. 콘솔 앱 템플릿을 선택합니다. 이름 상자에 SelfHost를 입력한 다음 확인을 선택합니다.

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

    솔루션 탐색기 창이 표시되어 있지 않으면 보기 메뉴에서 솔루션 탐색기를 선택합니다.

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

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

    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }
    
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }
    
    <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
    

    참고 항목

    서비스 인터페이스를 정의하고 구현하는 방법에 대한 자세한 내용은 방법: 서비스 계약 정의방법: 서비스 계약 구현을 참조하세요.

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

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

    // 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();
    }
    
    ' 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
    

    참고 항목

    이 예제에서는 기본 엔드포인트를 사용하며, 이 서비스에는 구성 파일이 필요하지 않습니다. 엔드포인트를 구성하지 않으면 런타임이 서비스에서 구현되는 각 서비스 계약의 각 기본 주소에 대해 엔드포인트를 하나씩 만듭니다. 기본 엔드포인트에 대한 자세한 내용은 단순화된 구성WCF 서비스의 단순화된 구성을 참조하세요.

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

서비스 테스트

  1. Ctrl+F5 키를 눌러 서비스를 실행합니다.

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

    WCF 테스트 클라이언트를 열려면 Visual Studio용 개발자 명령 프롬프트를 열고 WcfTestClient.exe를 실행합니다.

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

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

    서비스가 실행 중인지 확인하십시오. 그렇지 않으면 이 단계는 실패합니다. 코드에서 기본 주소를 변경한 경우에는 이 단계에서 수정된 기본 주소를 사용하십시오.

  5. 내 서비스 프로젝트 노드 아래의 SayHello를 두 번 클릭하고 요청 목록의 열에 사용자 이름을 입력한 다음 호출을 클릭합니다.

    그러면 응답 목록에 회신 메시지가 나타납니다.

예시

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

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("http://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();
            }
        }
    }
}
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("http://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

참고 항목