Host WCF to console application:
1. After you have created your WCF application now lets see how to host it in a console application.
2. Go to New Project and select console application. Now Add your working WCF Project to the Console application. To add right click on the solution file of the console app and go to "add existing project" option.
After u add the project it should look like this.
3. Right click on the console project and add reference of namespace System.servicemodel.
4. Now in the class file of the console application
add this below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
Uri baseAddress = new Uri("http://localhost:8080/ServiceWCFApp");
var host = new ServiceHost(
typeof(Service1),
baseAddress
);
host.AddServiceEndpoint(
typeof(IService1),
new BasicHttpBinding(),
"http://localhost:8080/ServiceWCFApp/ServiceWCF");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("The service is ready");
Console.ReadLine();
host.Close();
}
}
}
Note.: Make sure the namespace for all the project is the same.As in my case its "ConsoleApplication1".
5. Now run the project and in the console screen you should see the message as "The Service is Ready"
6. After this to check whether the service is hosted successfully or not.
Go to Visual studio 10 or 12 and then go to visual studio tools --> command prompt and type wcftestclient.exe and enter.
Go to file and add service, here copy the base address from the class file of the console app. click ok and test the hosted service.
No comments:
Post a Comment