Condividi tramite


Creating and hosting a minimal WCF Service in .NET 4

12th of March… that’s the date when we release Visual Studio 2010 and .NET Framework 4. I’m so excited and if you have a MSDN Subscription you can already download the Release Candidate right now. If you don’t have a MSDN Subscription you’ll have to wait some more hours before you can download the release candidate.

Anyway, I got into a discussion with my colleague about WCF and as I went along testing what we discussed I couldn’t help admiring how simple it is to get up and running with a WCF Service in .NET 4. The following example creates and hosts a WCF Service as a Web Service using basicHttpBinding and exposes the metadata, WSDL, if you just steer your browser to the address of the service. In this example https://localhost:4711/?wsdl . Also notice that no other configuration… I repeat. No other configuration is needed!

WCF will create default endpoints using default bindings and if you want to, you could override default behavior in this app by adding information in your application config file (app.config or web.config), but you don’t need to. This will make it tremendously easier to get up and running with your WCF Services.

Here you go:

    1: using System;
    2: using System.ServiceModel;
    3: using System.ServiceModel.Description;
    4:  
    5: namespace MinimalWebService
    6: {
    7:     class Program
    8:     {
    9:         static void Main()
   10:         {
   11:             using (var host = new ServiceHost(typeof(TimeService), new Uri("https://localhost:4711")))
   12:             {
   13:                 host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
   14:                 host.Open();
   15:  
   16:                 Console.WriteLine("Service is up'n running at {0}", host.Description.Endpoints[0].Address);
   17:                 Console.WriteLine("Press any key to shut down service");
   18:                 Console.ReadKey();
   19:             }
   20:         }
   21:     }
   22:  
   23:     [ServiceContract]
   24:     public class TimeService
   25:     {
   26:         [OperationContract]
   27:         public DateTime GetTime()
   28:         {
   29:             return DateTime.Now;
   30:         }
   31:     }
   32: }