Inline Coding in .svc Files in WCF
For IIS-hosted services in WCF there are two coding models: code inline and code behind. Code behind is the most common option for developers but code inline is a good choice when you want to build a service quickly and deploy it to server. In this post I want to discuss about inline coding in WCF when you're hosting your services on IIS.
In your .svc files, it's possible to put source code directly or add references to other source code files where you've written the code. In both cases services will be compiled on demand.
In first case, where you put your code logic in .svc file, there is nothing to care about and you can simply put your source code under directives but you must set the Service attribute of your ServiceHost directive to the name of your service's class. Here is an example:
<%@ServiceHost language="c#" Debug="true" Service="MyService.MyService" %>
using System;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace MyService
{
[ServiceContract]
public interface IServiceContract
{
[OperationContract]
int MyMethod(int x, int y);
}
public class MyService : IServiceContract
{
#region IServiceContract Members
public int MyMethod(int x, int y)
{
return ((x + y) * 2);
}
#endregion
}
}
The second option is to add references to external source code files as many as you like. In this case, you put your .cs or .vb source code files on server and add Assembly directive for them to .svc file. But rather than Name attribute of assembly, you must put a src attribute which refers to your source code files. In below code I declare my service contract in a separate file, named IServiceContract.cs.
using System;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace MyService
{
[ServiceContract]
public interface IServiceContract
{
[OperationContract]
int MyMethod(int x, int y);
}
}
And implement my code logic in .svc file.
<%@ServiceHost language="c#" Debug="true" Service="MyService.MyService" %>
<%@Assembly src="IServiceContract.cs" %>
using System;
using System.ServiceModel;
namespace MyService
{
public class MyService : IServiceContract
{
#region IServiceContract Members
public int MyMethod(int x, int y)
{
return ((x + y) * 2);
}
#endregion
}
}
Tip: In inline coding, one convenient way to have debugging features is to enable debugging by setting Debug attribute of ServiceHost directive to true but as is recommended in ASP.NET, you should disable it after deploying the service to server.
[advertisement] Axosoft OnTime 2008 is four developer tools in one: bug tracking, project wiki, feature management, and help desk. It manages your development process so developers can focus on coding. Installed or Hosted – Free Single-user license -- Free 30-day team trial.
1 Comment : 05.21.07

#1
DotNetKicks.com
05.21.2007 @ 10:12 AM