Short and simple here, I am going to show you how easy it is to host your Windows Communication Foundation web service in a console application. I am doing a console application so we can focus on the code involved, no so much an underlying project structure (we will get into that in some other posts). If you are following along from the last post, then you will want to open up the solution that we created in that one, because we are going to start from there. If you did not take a look at the last post, I would highly recommend it.
Ok and here we go. First right click your solution and add a new Console Application
NOTE: In the screen shots I named my project ServiceHost, which caused some issues down the road. I would just name it ConsoleHost to avoid any trouble.
Now select the Console Application:
Now we need to add two references to this new project: one the System.ServiceModel, and the other reference is to our WCF Library Project:
And once in there add the two references:
First thing to do is add the following code the the Main method.
Simple stuff happening here. We are using the ServiceHost Class to instantiate a new instant of our service we created. After that we are adding some endpoints by giving it the Service Contract reference, the protocol we will be using, and a url to map it to.
No we can add a try/catch statement to test this out. The following code simply opens up the connection, keeps it open under the user presses a key, then gracefully closes.
If you hit ctrl+F5 you should see the console window come up and just stay nice and empty until you press a key, and which point it will close. That is kinda lame, I am sure we would all like to see something indicating that things are as they should be. Now we will add a method that will print out some info the the console so we get the satisfaction we desire.
Now in your try statement in the Main Method add a call to PrintServiceInfo and pass it the host you created.
(so type PrintServiceInfo(host); for those who like to just see what to copy and paste)
Run that application again and you should see something like this:
So you may be thinking, "Wow that is the coolest thing I have ever seen!!", or you are likely thinking, "Ok what was the point of all this?".
This may not seem very useful, and perhaps it really isn't, but now we can all see how simple it is the actually host a WCF service. This is all the code it took:
Not sure I can complain about it being too-complex and unsightly now. Damn.
Check back in the next few days and I will get into some more robust examples and experiment with the best way to host these things in an MVC app.